Learn. Practice. Feel prepared.
Java Objective Questions and Answers
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 and verify answers.
1 Given: import java.util.regex.*; class Regex2 { public static void main(String[] args) { Pattern p = Pattern.compile(args[0]); Matcher m = p.matcher(args[1]); boolean b = false; while(b = m.find()) { System.out.print(m.start() + m.group()); } } } And the command line: java Regex2 "\d*" ab34ef What is the result?
Correct answer:
01234456
The \d is looking for digits. The * is a quantifier that looks for 0 to many
occurrences of the pattern that precedes it. Because we specified *, the group() method
returns empty Strings until consecutive digits are found, so the only time group() returns
a value is when it returns 34 when the matcher finds digits starting in position 2. The
start() method returns the starting position of the previous match because, again,
we said find 0 to many occurrences.
2 Given: import java.io.*; class Player { Player() { System.out.print("p"); } } class CardPlayer extends Player implements Serializable { CardPlayer() { System.out.print("c"); } public static void main(String[] args) { CardPlayer c1 = new CardPlayer(); try { FileOutputStream fos = new FileOutputStream("play.txt"); ObjectOutputStream os = new ObjectOutputStream(fos); os.writeObject(c1); os.close(); FileInputStream fis = new FileInputStream("play.txt"); ObjectInputStream is = new ObjectInputStream(fis); CardPlayer c2 = (CardPlayer) is.readObject(); is.close(); } catch (Exception x ) { } } } What is the result?
Correct answer:
pcp
It's okay for a class to implement Serializable even if its superclass doesn't.
However, when you deserialize such an object, the non-serializable superclass must run its
constructor. Remember, constructors don't run on deserialized classes that implement
Serializable.
3 Given: class TKO { public static void main(String[] args) { String s = "-"; Integer x = 343; long L343 = 343L; if(x.equals(L343)) s += ".e1 "; if(x.equals(343)) s += ".e2 "; Short s1 = (short)((new Short((short)343)) / (new Short((short)49))); if(s1 == 7) s += "=s "; if(s1 < new Integer(7+1)) s += "fly "; System.out.println(s); } } Which of the following will be included in the output String s? (Choose all that apply.) A. .e1 B. .e2 C. =s D. fly E. None of the above F. Compilation fails
Correct answer:
B, C, D
equals() method for the integer wrappers
will only return true if the two primitive types and the two values are equal. With C, it's
okay to unbox and use ==. For D, it's okay to create a wrapper object with an expression,
and unbox it for comparison with a primitive.
4 Which is true?
Correct answer:
"X extends Y" is correct if X and Y are either both classes or both interfaces
A is incorrect because classes implement interfaces, they don't extend them. B is incorrect
because interfaces only "inherit from" other interfaces. D is incorrect based on the
preceding rules.
5 Given: 1. class Voop { 2. public static void main(String[] args) { 3. doStuff(1); 4. doStuff(1,2); 5. } 6. // insert code here 7. } Which, inserted independently at line 6, will compile? (Choose all that apply.) A. static void doStuff(int... doArgs) { } B. static void doStuff(int[] doArgs) { } C. static void doStuff(int doArgs...) { } D. static void doStuff(int... doArgs, int y) { } E. static void doStuff(int x, int... doArgs) { }
Correct answer:
A, E
B and C are invalid var-arg syntax, and D is invalid because the var-arg must be the last
of a method's arguments. (
6 Given: 1. enum Animals { 2. DOG("woof"), CAT("meow"), FISH("burble"); 3. String sound; 4. Animals(String s) { sound = s; } 5. } 6. class TestEnum { 7. static Animals a; 8. public static void main(String [] args) { 9. System.out.println(a.DOG.sound + " " + a.FISH.sound); 10. } 11. } What is the result?
Correct answer:
woof burble
enums can have constructors and variables
7 Given two files: 1. package pkgA; 2. public class Foo { 3. int a = 5; 4. protected int b = 6; 5. public int c = 7; 6. } 3. package pkgB; 4. import pkgA.*; 5. public class Baz { 6. public static void main(String[] args) { 7. Foo f = new Foo(); 8. System.out.print(" " + f.a); 9. System.out.print(" " + f.b); 10. System.out.print(" " + f.c); 11. } 12. } What is the result? (Choose all that apply.) A. 5 6 7 B. 5 followed by an exception C. Compilation fails with an error on line 7 D. Compilation fails with an error on line 8 E. Compilation fails with an error on line 9 F. Compilation fails with an error on line 10
Correct answer:
D , E
Variable a has default access, so it cannot be accessed from outside the
package. Variable b has protected access in pkgA
8 Given: 1. public class Electronic implements Device { public void doIt() { } } 2. 3. abstract class Phone1 extends Electronic { } 4. 5. abstract class Phone2 extends Electronic { public void doIt(int x) { } } 6. 7. class Phone3 extends Electronic implements Device { public void doStuff() { } } 8. 9. interface Device { public void doIt(); }
Correct answer:
Compilation succeeds
9 Given: 4. class Announce { 5. public static void main(String[] args) { 6. for(int __x = 0; __x < 3; __x++) ; 7. int #lb = 7; 8. long [] x [5]; 9. Boolean []ba[]; 10. enum Traffic { RED, YELLOW, GREEN }; 11. } 12. } What is the result? (Choose all that apply.) A. Compilation succeeds B. Compilation fails with an error on line 6 C. Compilation fails with an error on line 7 D. Compilation fails with an error on line 8 E. Compilation fails with an error on line 9 F. Compilation fails with an error on line 10
Correct answer:
C, D, F
Variable names cannot begin with a #, an array declaration can’t
include a size without an instantiation, and enums can’t be declared within a method
10 Given: 3. public class TestDays { 4. public enum Days { MON, TUE, WED }; 5. public static void main(String[] args) { 6. for(Days d : Days.values() ) 7. ; 8. Days [] d2 = Days.values(); 9. System.out.println(d2[2]); 10. } 11. } What is the result?
Correct answer:
WED
Every enum comes with a static values() method that returns an array
of the enum's values, in the order in which they are declared in the enum.
11 Given: 4. public class Frodo extends Hobbit { 5. public static void main(String[] args) { 6. Short myGold = 7; 7. System.out.println(countGold(myGold, 6)); 8. } 9. } 10. class Hobbit { 11. int countGold(int x, int y) { return x + y; } 12. } What is the result?
Correct answer:
Compilation fails due to an error on line 7
The Short myGold is autoboxed correctly, but the countGold() method cannot be invoked from a static context
12 Which statements are true about comparing two instances of the same class, given that the equals() and hashCode() methods have been properly overridden? (Choose all that apply.) A. If the equals() method returns true, the hashCode() comparison == might return false B. If the equals() method returns false, the hashCode() comparison == might return true C. If the hashCode() comparison == returns true, the equals() method must return true D. If the hashCode() comparison == returns true, the equals() method might return true E. If the hashCode() comparison != returns true, the equals() method might return true
Correct answer:
B, D
B is true because often two dissimilar objects can return the same hashcode value. D is true because if the hashCode() comparison returns ==, the two objects might or might not be equal.
13 Given: public static void before() { Set set = new TreeSet(); set.add("2"); set.add(3); set.add("1"); Iterator it = set.iterator(); while (it.hasNext()) System.out.print(it.next() + " "); } Which statements are true?
Correct answer:
The before() method will throw an exception at runtime
You can't put both Strings and ints into the same TreeSet. Without generics, the compiler has no way of knowing what type is appropriate for this TreeSet, so it allows everything to compile. At runtime, the TreeSet will try to sort the elements as they're added, and when it tries to compare an Integer with a String it will throw a ClassCastException. Note that although the before() method does not use generics, it does use autoboxing. Watch out for code that uses some new features and some old features mixed together.
14 Given: import java.util.*; class MapEQ { public static void main(String[] args) { Map<ToDos, String> m = new HashMap<ToDos, String>(); ToDos t1 = new ToDos("Monday"); ToDos t2 = new ToDos("Monday"); ToDos t3 = new ToDos("Tuesday"); m.put(t1, "doLaundry"); m.put(t2, "payBills"); m.put(t3, "cleanAttic"); System.out.println(m.size()); } } class ToDos{ String day; ToDos(String d) { day = d; } public boolean equals(Object o) { return ((ToDos)o).day == this.day; } // public int hashCode() { return 9; } } Which is correct? (Choose all that apply.) A. As the code stands it will not compile B. As the code stands the output will be 2 C. As the code stands the output will be 3 D. If the hashCode() method is uncommented the output will be 2 E. If the hashCode() method is uncommented the output will be 3
Correct answer:
C, D
If hashCode() is not overridden then every entry will go into its own bucket, and the overridden equals() method will have no effect on determining equivalency.
If hashCode() is overridden, then the overridden equals() method will view t1 and t2 as duplicates.
15 Given: class Top { public Top(String s) { System.out.print("B"); } } public class Bottom2 extends Top { public Bottom2(String s) { System.out.print("D"); } public static void main(String [] args) { new Bottom2("C"); System.out.println(" "); } } What is the result?
Correct answer:
Compilation fails
The implied super() call in Bottom2’s constructor cannot be satisfied because there isn’t a no-arg constructor in Top. A default, no-arg constructor is generated by the compiler only if the class has no constructor defined explicitly.