Java MCQ Output based Questions - Arrays
In this article, we will cover some Java MCQ output based questions which will help extend your Java knowledge. Usually In Interviews nowadays, interviewer are more focused on negative questions rather than conceptual questions, and If you go through below questions, It will surely give you an add on and add value to your experience.
Java MCQ Output based Questions
Arrays in Java
import java.util.*;
public class Test {
public static void main(String[] args)
{
int[] x = new int[3];
System.out.println("x[0] is " + x[0]);
}
}
A. The program has a compile error because the size of the array wasn’t specified when declaring the array.
B. The program has a runtime error because the array elements are not initialized.
C. The program runs fine and displays x[0] is 0.
D. The program has a runtime error because the array element x[0] is not defined.
Explanation - Program is syntactically correct, so no error. In java, if the array is not initialized at the time of declaration and creation then all the elements of the array are initialized to 0 by default.
import java.util.*;
public class Test {
public static void main(String[] args)
{
int[] x = { 120, 200, 016 };
for (int i = 0; i < x.length; i++)
System.out.print(x[i] + " ");
}
}
A. 120 200 16
B. 120 200 14
C. 120 200 016
D. 016 is a compile error. It should be written as 16.
Explanation - 016 is an octal number. The prefix 0 indicates that a number is in octal and in octal 16 is equal to 14.
import java.util.*;
public class Test {
public static void main(String args[])
{
String s1 = "java";
String s2 = "java";
System.out.println(s1.equals(s2));
System.out.println(s1 == s2);
}
}
A. false true
B. false false
C. true false
D. true true
import java.util.*;
public class Test {
public static void main(String[] args)
{
int[] x = { 1, 2, 3, 4 };
int[] y = x;
x = new int[2];
for (int i = 0; i < x.length; i++)
System.out.print(y[i] + " ");
}
}
A. 1 2 3 4
B. 0 0 0 0
C. 1 2
D. 0 0
Explanation - The length of x array is 2. So the loop will execute from i=0 to i=1.
class selection_statements {
public static void main(String args[])
{
int var1 = 5;
int var2 = 6;
if ((var2 = 1) == var1)
System.out.print(var2);
else
System.out.print(++var2);
}
}
a) 1
b) 2
c) 3
d) 4
class comma_operator {
public static void main(String args[])
{
int sum = 0;
for (int i = 0, j = 0; i < 5 & j < 5; ++i, j = i + 1)
sum += i;
System.out.println(sum);
}
}
a) 5
b) 6
c) 14
d) compilation error
Explanation - Using comma operator, we can include more than one statement in the initialization and iteration portion of the for loop. Therefore both ++i and j = i + 1 is executed i gets the value : 0, 1, 2, 3, and j gets the values : 0, 1, 2, 3, 4, 5.
Comments
Post a Comment