Sharpen your Core Java fundamentals with carefully curated multiple-choice questions covering Strings, Exception Handling, Collections Framework, Multithreading, JVM internals, Memory Management, OOP concepts, and more.
Practice Java MCQs with Detailed Explanations
Answer at least
12
questions to submit.
76.
Which are true? (Choose all that apply.)
A. It is appropriate to use assertions to validate arguments to methods marked public
B. It is appropriate to catch and handle assertion errors
C. It is NOT appropriate to use assertions to validate command-line arguments
D. It is appropriate to use assertions to generate alerts when you reach code that should not
be reachable
E. It is NOT appropriate for assertions to change a program’s state
Correct answer:C, D, E
A is incorrect. It is acceptable to use assertions to test the arguments of private methods. B is incorrect. While assertion errors can be caught, Sun discourages you from doing so.
77.
Given:
class Emu {
static String s = "-";
public static void main(String[] args) {
try {
throw new Exception();
} catch (Exception e) {
try {
try { throw new Exception();
} catch (Exception ex) { s += "ic "; }
throw new Exception(); }
catch (Exception x) { s += "mc "; }
finally { s += "mf "; }
} finally { s += "of "; }
System.out.println(s);
} }
What is the result?
Correct answer:-ic mc mf of
There is no problem nesting try / catch blocks. As is normal, when an exception is thrown, the code in the catch block runs, then the code in the finally block
runs.
78.
Given:
3. class SubException extends Exception { }
4. class SubSubException extends SubException { }
5.
6. public class CC { void doStuff() throws SubException { } }
7.
8. class CC2 extends CC { void doStuff() throws SubSubException { } }
9.
10. class CC3 extends CC { void doStuff() throws Exception { } }
11.
12. class CC4 extends CC { void doStuff(int x) throws Exception { } }
13.
14. class CC5 extends CC { void doStuff() { } }
What is the result?
Correct answer:Compilation fails due to an error on line 10
An overriding method cannot throw a broader exception than the method it's overriding. Class CC4's method is an overload, not an override.
79.
Given:
3. public class Ebb {
4. static int x = 7;
5. public static void main(String[] args) {
6. String s = "";
7. for(int y = 0; y < 3; y++) {
8. x++;
9. switch(x) {
10. case 8: s += "8 ";
11. case 9: s += "9 ";
12. case 10: { s+= "10 "; break; }
13. default: s += "d ";
14. case 13: s+= "13 ";
15. }
16. }
17. System.out.println(s);
18. }
19. static { x++; }
20. }
What is the result?
Correct answer:9 10 10 d 13
Did you catch the static initializer block? Remember that switches work on "fall-thru" logic, and that fall-thru logic also applies to the default case, which is used when
no other case matches
80.
Which three form part of correct array declarations?
1. public int a [ ]
2. static int [ ] a
3. public [ ] int a
4. private int a [3]
5. private int [3] a [ ]
6. public final int [ ] a
Correct answer:1, 2, 6
Option (3) is not a correct array declaration. The compiler complains with: illegal start of type. The brackets are in the wrong place. The following would work: public int[ ] a
Option (4) is not a correct array declaration. The compiler complains with: ']' expected. A closing bracket is expected in place of the 3. The following works: private int a []
Option (5) is not a correct array declaration.
The compiler thinks you are trying to create two arrays because there are two array initialisers to the right of the equals, whereas your intention was to create one 3 x 3 two-dimensional array.
To correct the problem and make option B compile you need to add an extra pair of curly brackets:
82.
Which class does not override the equals() and hashCode() methods, inheriting them directly from class Object?
Correct answer:java.lang.StringBuffer
83.
Which interface does java.util.Hashtable implement?
Correct answer:Java.util.Map
84.
/* Missing Statement ? */
public class foo
{
public static void main(String[]args)throws Exception
{
java.io.PrintWriter out = new java.io.PrintWriter();
new java.io.OutputStreamWriter(System.out,true);
out.println("Hello");
}
}
What line of code should replace the missing statement to make this program compile?
Correct answer:No statement required.
The usual method for using/importing the java packages/classes is by using an import statement at the top of your code. However it is possible to explicitly import the specific class that you want to use as you use it which is shown in the code above. The disadvantage of this however is that every time you create a new object you will have to use the class path in the case "java.io" then the class name in the long run leading to a lot more typing.
85.
Given:
3. public class Circles {
4. public static void main(String[] args) {
5. int[] ia = {1,3,5,7,9};
6. for(int x : ia) {
7. for(int j = 0; j < 3; j++) {
8. if(x > 4 && x < 8) continue;
9. System.out.print(" " + x);
10. if(j == 1) break;
11. continue;
12. }
13. continue;
14. }
15. }
16. }
What is the result?
Correct answer:1 1 3 3 9 9
The basic rule for unlabeled continue statements is that the current iteration stops early and execution jumps to the next iteration. The last two continue statements are redundant!
86.
Given:
3. public class Wind {
4. public static void main(String[] args) {
5. foreach:
6. for(int j=0; j<5; j++) {
7. for(int k=0; k< 3; k++) {
8. System.out.print(" " + j);
9. if(j==3 && k==1) break foreach;
10. if(j==0 || j==2) break;
11. }
12. }
13. }
14. }
What is the result?
Correct answer:0 1 1 1 2 3 3
break breaks out of the current innermost loop and continues. A labeled
break breaks out of and terminates the current loops
87.
Given:
3. public class Clumsy {
4. public static void main(String[] args) {
5. int j = 7;
6. assert(++j > 7);
7. assert(++j > 8): "hi";
8. assert(j > 10): j=12;
9. assert(j==12): doStuff();
10. assert(j==12): new Clumsy();
11. }
12. static void doStuff() { }
13. }
Which are true?
Correct answer:Compilation fails due to an error on line 9
When an assert statement has two expressions, the second expression must return a value. The only two-expression assert statement that doesn’t return a value is on line 9.
88.
Given:
class Hexy {
public static void main(String[] args) {
Integer i = 42;
String s = (i<40)?"life":(i>50)?"universe":"everything";
System.out.println(s);
}
}
What is the result?
Correct answer:everything
Fragments F2, F3, and F5 will compile, and only F3 is true.
89.
Given:
class Fork {
public static void main(String[] args) {
if(args.length == 1 | args[1].equals("test")) {
System.out.println("test case");
} else {
System.out.println("production " + args[0]);
}
}
}
And the command-line invocation:
java Fork live2
What is the result?
Correct answer:An exception is thrown at runtime
Because the short circuit (||) is not used, both operands are evaluated. Since args[1] is past the args array bounds, an ArrayIndexOutOfBoundsException is thrown.
90.
Given:
3. public class Twisty {
4. { index = 1; }
5. int index;
6. public static void main(String[] args) {
7. new Twisty().go();
8. }
9. void go() {
10. int [][] dd = {{9,8,7}, {6,5,4}, {3,2,1,0}};
11. System.out.println(dd[index++][index++]);
12. }
13. }
What is the result?
Correct answer:6
Multidimensional arrays' dimensions can be inconsistent, the code uses an initialization block, and the increment operators are both post-increment operators
91.
Given:
3. public class McGee {
4. public static void main(String[] args) {
5. Days d1 = Days.TH;
6. Days d2 = Days.M;
7. for(Days d: Days.values()) {
8. if(d.equals(Days.F)) break;
9. d2 = d;
10. }
11. System.out.println((d1 == d2)?"same old" : "newly new");
12. }
13. enum Days {M, T, W, TH, F, SA, SU};
14. }
What is the result?
Correct answer:same old
All of this syntax is correct. The for-each iterates through the enum using the values() method to return an array. Enums can be compared using either equals() or ==. Enums can be used in a ternary operator's Boolean test.
92.
Given:
4. public class SpecialOps {
5. public static void main(String[] args) {
6. String s = "";
7. Boolean b1 = true;
8. Boolean b2 = false;
9. if((b2 = false) | (21%5) > 2) s += "x";
10. if(b1 || (b2 = true)) s += "y";
11. if(b2 == true) s += "z";
12. System.out.println(s);
13. }
14. }
Which are true?
Correct answer:y will be included in the output
First of all, boxing takes care of the Boolean. Line 9 uses the modulus operator,which returns the remainder of the division, which in this case is 1. Also, line 9 sets b2 to false, and it doesn't test b2's value. Line 10 sets b2 to true, and it doesn’t test its value; however, the short circuit operator keeps the expression b2 = true from being executed
93.
Given:
3. interface Vessel { }
4. interface Toy { }
5. class Boat implements Vessel { }
6. class Speedboat extends Boat implements Toy { }
7. public class Tree {
8. public static void main(String[] args) {
9. String s = "0";
10. Boat b = new Boat();
11. Boat b2 = new Speedboat();
12. Speedboat s2 = new Speedboat();
13. if((b instanceof Vessel) && (b2 instanceof Toy)) s += "1";
14. if((s2 instanceof Vessel) && (s2 instanceof Toy)) s += "2";
15. System.out.println(s);
16. }
17. }
What is the result?
Correct answer:012
First, remember that instanceof can look up through multiple levels of an inheritance tree. Also remember that instanceof is commonly used before attempting a downcast, so in this case, after line 15, it would be possible to say Speedboat s3 =(Speedboat)b2;.
94.
Given :
public class MyThreads {
private static class MyDaemonThread extends Thread {
public MyDaemonThread() {
setDaemon(true);
}
@Override
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
}
}
public static void main(String[] args) throws InterruptedException {
Thread thread = new MyDaemonThread();
thread.start();
thread.join();
System.out.println(thread.isAlive());
}
}
What is the result?
Correct answer:false
The output of the above code is “false”. Although the instance of MyDaemonThread is a daemon thread, the invocation of join() causes the main thread(currently running thread) to wait until the execution of the daemon thread has finished. Hence calling isAlive() on the thread instance reveals that the daemon thread is no longer running.