MCQ Questions

Question Bank › Technical › Java › MCQ

123

Access Modifiers

Q1.Easy
You want subclasses located in any package to be able to access members of a superclass. Which is the most restrictive access modifier that achieves this?
  1. public
  2. private
  3. protected
  4. transient
Show answer & explanation
Answer: (C) protected
Explanation: 1. private restricts access to the same class only — too restrictive. 2. Default (package-private) allows access only within the same package, not subclasses in other packages. 3. protected allows access within the same package and also to subclasses in any package — this meets the requirement. 4. public also works but is less restrictive than protected. 5. transient is not an access modifier. So the most restrictive modifier that works is protected.
Q2.Easy
You want a class to access members of another class that resides in the same package, but you want the most restrictive access level that still allows this. Which access modifier should you use?
  1. public
  2. private
  3. protected
  4. default (no modifier)
Show answer & explanation
Answer: (D) default (no modifier)
Explanation: 1. private restricts access to the same class only — too restrictive. 2. default (package-private) allows access to all classes in the same package — exactly what is needed. 3. protected allows same-package plus subclasses — broader than needed. 4. public allows access everywhere — the least restrictive. So the most restrictive option that still works is default access.
Q3.Easy
A method is declared inside a class. Which access modifier restricts that method so it can be accessed only by other members of the same class?
  1. final
  2. static
  3. private
  4. protected
  5. volatile
Show answer & explanation
Answer: (C) private
Explanation: 1. 'private' members are visible only within the same class, which matches the requirement. 2. 'final' and 'static' are not access modifiers (they control overriding and instance vs class level). 3. 'protected' allows access to subclasses and same-package classes, which is broader than required. 4. 'volatile' is a field modifier, not an access modifier.
Q4.Easy
Which is the most restrictive access modifier that still allows members of one class to access members of another class located in the same package?
  1. public
  2. abstract
  3. protected
  4. synchronized
  5. default access
Show answer & explanation
Answer: (E) default access
Explanation: 1) public and protected are less restrictive than package access. 2) abstract and synchronized are not access modifiers at all. 3) Default (package-private) access lets any class in the same package access the member, but no class outside the package. 4) Therefore default access is the most restrictive modifier that still permits same-package access.

Anonymous Inner Classes

Q5.Medium
Which statement is true about an anonymous inner class in Java?
  1. It can extend exactly one class and implement exactly one interface.
  2. It can extend exactly one class and can implement multiple interfaces.
  3. It can extend exactly one class or implement exactly one interface.
  4. It can implement multiple interfaces regardless of whether it also extends a class.
Show answer & explanation
Answer: (C) It can extend exactly one class or implement exactly one interface.
Explanation: 1. An anonymous inner class is written as new <Type>() { ... }. 2. Only one type name may follow new. 3. That single type is either a class (the anonymous class extends it) or an interface (the anonymous class implements it). 4. Therefore it can extend one class OR implement one interface, but not both and not multiple interfaces. 5. This matches option C.
Q6.Medium
In Java, which of the following correctly creates an instance of an anonymous inner class that implements the Runnable interface?
  1. Runnable r = new Runnable() { };
  2. Runnable r = new Runnable(public void run() { });
  3. Runnable r = new Runnable { public void run(){}};
  4. Runnable r = new Runnable() { public void run() { } };
Show answer & explanation
Answer: (D) Runnable r = new Runnable() { public void run() { } };
Explanation: 1. An anonymous inner class is written as 'new InterfaceName() { ... }' with parentheses after the type name. 2. Because Runnable is an interface, the anonymous class must override run(). 3. Option A has no run() method, so it fails to implement the interface. 4. Options B and C use wrong syntax (no parentheses / method inside constructor call). 5. Option D uses correct syntax and overrides run(), so it compiles and creates the anonymous instance.
Q7.Medium
What will be the output of the following Java program?

public static void main(String[] args) {
    Object obj = new Object() {
        public int hashCode() {
            return 57;
        }
    };
    System.out.println(obj.hashCode());
}
  1. 57
  2. Runtime Exception
  3. Compile Error at line 2
  4. Compile Error at line 5
Show answer & explanation
Answer: (A) 57
Explanation: 1) This uses an anonymous inner class that extends Object and overrides hashCode(). 2) The anonymous class is legal; no name is needed and 'new Object() {...}' is valid. 3) The overridden hashCode() returns 57. 4) obj.hashCode() calls the overridden method, so 57 is printed.

Assertions

Q8.Easy
What will be the output of the program when run with the -ea option?

public class Demo {
    public static void main(String[] args) {
        int n = 0;
        assert (n > 0) : "check failed";  /* Line 6 */
        System.out.println("completed");
    }
}
  1. completed
  2. Compilation fails.
  3. An AssertionError is thrown.
  4. An AssertionError is thrown and completed is output.
Show answer & explanation
Answer: (C) An AssertionError is thrown.
Explanation: 1. With -ea, assertions are enabled at runtime. 2. n is 0, so the condition (n > 0) is false. 3. The assert therefore throws an AssertionError with the detail message "check failed". 4. Program control leaves main immediately, so "completed" is never printed. 5. Hence the output is an AssertionError being thrown.
Q9.Medium
What will be the output of the program?
public class Test {
    public static void main(String[] args) {
        int x = 0;
        assert (x > 0) ? "assertion failed" : "assertion passed";
        System.out.println("finished");
    }
}
  1. finished
  2. Compilation fails.
  3. An AssertionError is thrown and finished is output.
  4. An AssertionError is thrown with the message "assertion failed."
Show answer & explanation
Answer: (B) Compilation fails.
Explanation: The assert statement requires a boolean expression. The ternary operator (x > 0) ? "assertion failed" : "assertion passed" evaluates to a String, not a boolean. Therefore, the code does not compile. The assert statement cannot be used like a ternary operator to produce a message.
Q10.Medium
public class Test {
    public void foo() {
        assert false; /* Line 5 */
        assert false; /* Line 6 */
    }
    public void bar() {
        while (true) {
            assert false; /* Line 12 */
        }
        assert false; /* Line 14 */
    }
}
What causes compilation to fail?
  1. Line 5
  2. Line 6
  3. Line 12
  4. Line 14
Show answer & explanation
Answer: (D) Line 14
Explanation: In method bar(), the while(true) loop is infinite and contains no break statement, so the code after the loop (line 14) is unreachable. Java requires that every statement must be reachable; otherwise, a compile-time error occurs. Lines 5, 6, and 12 are reachable because assertions do not affect reachability in that way.
Q11.Medium
Which statement is true?
  1. Assertions can be enabled or disabled on a class-by-class basis.
  2. Conditional compilation is used to allow tested classes to run at full speed.
  3. Assertions are appropriate for checking the validity of arguments in a method.
  4. The programmer can choose to execute a return statement or to throw an exception if an assertion fails.
Show answer & explanation
Answer: (A) Assertions can be enabled or disabled on a class-by-class basis.
Explanation: Java allows assertion status to be set per class or per package using command-line options like -ea or -da. Option B is false because Java does not have conditional compilation. Option C is false because assertions are not suitable for public method argument validation; explicit checks should be used. Option D is false because assertion failures throw AssertionError, which should not be caught and handled.
Q12.Medium
Which statement is true about assertions in Java?
  1. Assertion expressions should not contain side effects.
  2. Assertion expression values can be any primitive type.
  3. Assertions should be used for enforcing preconditions on public methods.
  4. An AssertionError thrown as a result of a failed assertion should always be handled by the enclosing method.
Show answer & explanation
Answer: (A) Assertion expressions should not contain side effects.
Explanation: Assertions may be disabled at runtime, so the boolean expression inside an assertion might not be evaluated. If the expression has side effects, the program behavior could differ depending on whether assertions are enabled. Therefore, assertion expressions should be free of side effects. Option B is false because the expression must be boolean, not any primitive. Option C is false because assertions are not recommended for public method preconditions; explicit checks should be used. Option D is false because assertion failures should not be caught and handled.
Q13.Medium
What will be the output of the program?

public class Sample {
    public static int total;
    public static void show(int x) {
        System.out.print("show ");
        total = x;
    }
    public static int store(int z) {
        System.out.print("store ");
        return total = z;
    }
    public static void main(String[] args) {
        int t = 0;
        assert t > 0 : store(7);
        assert t > 1 : show(8);  /* Line 18 */
        System.out.println("done");
    }
}
  1. store
  2. store done
  3. show done
  4. Compilation fails
Show answer & explanation
Answer: (D) Compilation fails
Explanation: 1. The message expression after the colon in an assert must produce a value. 2. store(7) returns an int, so the first assert is fine. 3. show(8) has return type void, so it cannot be used as the message expression. 4. Line 18 therefore causes a compilation error. 5. Hence the program does not compile.
Q14.Medium
Which of the following statements about assertions is true?
  1. It is sometimes good practice to throw an AssertionError explicitly.
  2. Private getter() and setter() methods should not use assertions to verify their arguments.
  3. If an AssertionError is thrown inside a try-catch block, the finally block will be bypassed.
  4. It is proper to handle assertion statement failures using a catch (AssertionException ae) block.
Show answer & explanation
Answer: (A) It is sometimes good practice to throw an AssertionError explicitly.
Explanation: 1. Option A is true: sometimes you want an assertion-style failure even when assertions are disabled, so throwing AssertionError explicitly is acceptable. 2. Option B is false: it is considered appropriate to check argument values in private methods using assertions. 3. Option C is false: a finally block is never bypassed, even when an Error is thrown. 4. Option D is false: there is no AssertionException class, and AssertionErrors should not be caught. 5. So the only true statement is the first one.
Q15.Medium
Which of the following statements about Java assertions is true?
  1. In an assert statement, the expression after the colon ( : ) can be any Java expression, including one that returns void.
  2. If a switch block has no default case, adding an assert in place of a default is considered appropriate.
  3. In an assert statement, if the expression after the colon ( : ) has no value, the assert's error message will simply be empty.
  4. It is appropriate to handle assertion failures using a catch clause.
Show answer & explanation
Answer: (B) If a switch block has no default case, adding an assert in place of a default is considered appropriate.
Explanation: 1. Option A is false: the expression after the colon must produce a value, so a void method call is illegal. 2. Option B is true: adding an assertion where a switch has no default is a recognised good use of assertions. 3. Option C is false: the expression after the colon must have a value; it cannot be valueless. 4. Option D is false: assertion failures throw AssertionError (an Error, not an Exception) and should not be caught. 5. Therefore the correct statement is the one about the switch default.
Q16.Medium
Consider this Java program:

public class Check {
    public static int count;
    public static int doubleIt(int n) { return n * 2; }
    public static void main(String[] args) {
        int k = 6;
        assert k > 0;            /* Line 11 */
        assert k > 2 : doubleIt(k); /* Line 12 */
        if (k < 8)
            assert k > 4;        /* Line 14 */
        if (k < 12)
            assert k > 4 : k++;  /* Line 22 */
        System.out.println(k);
    }
}

Which line shows an inappropriate use of assertions?
  1. Line 11
  2. Line 12
  3. Line 14
  4. Line 22
Show answer & explanation
Answer: (D) Line 22
Explanation: 1. Assertions must not change program state; they should only check conditions. 2. Line 11 just checks k > 0 — fine. 3. Line 12 uses doubleIt(k) as the message expression; calling a method that returns a value is allowed — fine. 4. Line 14 is a conditional assert, which is legal — fine. 5. Line 22 uses k++ as the message expression, which modifies k as a side effect. If assertions are disabled the value of k changes differently, so this is inappropriate. 6. Hence Line 22 is the inappropriate use.
Q17.Hard
Which three of the following statements about Java assertions are true?
1. Assertion checking is typically enabled when a program is deployed.
2. It is never appropriate to write code to handle failure of an assert statement.
3. Assertion checking is typically enabled during program development and testing.
4. Assertion checking can be selectively enabled or disabled on a per-package basis, but not on a per-class basis.
5. Assertion checking can be selectively enabled or disabled on both a per-package basis and a per-class basis.
  1. 1, 2 and 4
  2. 2, 3 and 5
  3. 3, 4 and 5
  4. 1, 2 and 5
Show answer & explanation
Answer: (B) 2, 3 and 5
Explanation: 1) Statement 1 is false: assertions are normally disabled in deployed code. 2) Statement 2 is true: you should not write code to recover from an assertion failure. 3) Statement 3 is true: assertions are used during development and testing. 4) Statement 4 is false because statement 5 is true. 5) Statement 5 is true: assertions can be enabled/disabled per package and per class (using -ea/-da with package or class names). 6) Hence the true statements are 2, 3 and 5.

Exception Handling

Q18.Easy
What will be the output of this program?

public class Demo {
    public static void main(String[] args) {
        try {
            return;
        } finally {
            System.out.println("Cleanup");
        }
    }
}
  1. Cleanup
  2. Compilation fails.
  3. The code runs with no output.
  4. An exception is thrown at runtime.
Show answer & explanation
Answer: (A) Cleanup
Explanation: 1. Execution enters the try block and hits the return statement. 2. Before the method actually returns, the finally block is executed. 3. The finally block prints Cleanup. 4. Then the method returns, so the output is Cleanup.
Q19.Easy
What will be the output of this program?

class Base extends Exception { }
class Derived extends Base { }

public class Demo {
    public static void main(String[] args) {
        try {
            throw new Derived();
        } catch (Base b) {
            System.out.println("Base caught");
        } catch (Exception e) {
            System.out.println("Exception caught");
        }
    }
}
  1. Base caught
  2. Exception caught
  3. Compilation fails because of an error in the class Derived declaration.
  4. Compilation fails because of an error at the throw statement.
Show answer & explanation
Answer: (A) Base caught
Explanation: 1. Derived extends Base, so a Derived object is also a Base. 2. throw new Derived() throws a Derived exception. 3. The first catch (Base b) matches because Derived is a Base, so it prints Base caught. 4. The second catch is skipped. 5. There is no finally block, so the program ends normally.
Q20.Easy
What will be the output of the program? public class Demo { public static void main(String[] args) { try { safeCall(); System.out.print("X"); } catch (Exception ex) { System.out.print("Y"); } finally { System.out.print("Z"); } System.out.print("W"); } public static void safeCall() {} }
  1. XZ
  2. YZ
  3. XZW
  4. XYZW
Show answer & explanation
Answer: (C) XZW
Explanation: 1) safeCall() does nothing, so no exception is thrown. 2) Control returns to the try block and prints X. 3) The catch block is skipped because there is no exception. 4) The finally block always runs, printing Z. 5) Execution continues after the try statement, printing W. 6) Combined output: XZW.
Q21.Medium
What will be the output of the following Java program?

public class Test {
  public static void main(String[] args) {
    try {
      int a = 0;
      int b = 10 / a;
    } catch (Exception e) {
      System.out.println("Exception");
    } catch (ArithmeticException ae) {
      System.out.println("Arithmetic Exception");
    }
    System.out.println("finished");
  }
}
  1. finished
  2. Exception
  3. Compilation fails.
  4. Arithmetic Exception
Show answer & explanation
Answer: (C) Compilation fails.
Explanation: 1. ArithmeticException is a subclass of Exception. 2. The first catch block catches Exception, which already covers ArithmeticException. 3. The second catch block for ArithmeticException becomes unreachable, so the compiler reports an error. 4. More specific exceptions must be caught before more general ones. 5. Hence the program does not compile.
Q22.Medium
Consider this program:

public class Demo {
    public static void throwit() {
        throw new RuntimeException();
    }
    public static void main(String[] args) {
        try {
            System.out.println("Start");
            throwit();
            System.out.println("End of try");
        } finally {
            System.out.println("Cleanup");
        }
    }
}

Which option most closely describes the behaviour of the program?
  1. The program will not compile.
  2. The program will print Start, then report that a RuntimeException occurred, then print End of try, then print Cleanup.
  3. The program will print Start, then report that a RuntimeException occurred, and then print Cleanup.
  4. The program will print Start, then print Cleanup, then report that a RuntimeException occurred.
Show answer & explanation
Answer: (D) The program will print Start, then print Cleanup, then report that a RuntimeException occurred.
Explanation: 1. main prints Start. 2. throwit() throws a RuntimeException that is not caught anywhere. 3. Because the exception is uncaught, the line printing End of try is skipped. 4. The finally block executes before the exception propagates, printing Cleanup. 5. After the finally block, the uncaught exception terminates the program with an error message. 6. So the order is Start, Cleanup, then the error report.
Q23.Medium
What will be the output of this program?

public class Demo {
    public static void main(String[] args) {
        try {
            risky();
            System.out.print("P");
        } catch (Exception ex) {
            System.out.print("Q");
        } finally {
            System.out.print("R");
        }
        System.out.print("S");
    }
    public static void risky() {
        throw new Error();
    }
}
  1. PQRS
  2. Compilation fails.
  3. R is printed before the program exits with an error message.
  4. QR is printed before the program exits with an error message.
Show answer & explanation
Answer: (C) R is printed before the program exits with an error message.
Explanation: 1. risky() throws an Error, which is not a subclass of Exception. 2. The catch (Exception) block cannot catch an Error, so Q is not printed. 3. The finally block always runs, so R is printed. 4. The uncaught Error then propagates and terminates the program with an error message. 5. Hence only R is printed before exit.
Q24.Medium
What will be the output of this program?

public class Demo {
    public static void main(String[] args) {
        try {
            risky();
            System.out.print("P");
        } catch (RuntimeException ex) {
            System.out.print("Q");
        } catch (Exception ex1) {
            System.out.print("R");
        } finally {
            System.out.print("S");
        }
        System.out.print("T");
    }
    public static void risky() {
        throw new RuntimeException();
    }
}
  1. QS
  2. QRS
  3. QST
  4. QRST
Show answer & explanation
Answer: (C) QST
Explanation: 1. risky() throws a RuntimeException, so the line printing P is skipped. 2. The first catch (RuntimeException) matches and prints Q. 3. The second catch (Exception) is skipped because the exception is already handled. 4. The finally block always runs, printing S. 5. Execution continues after the try-catch-finally, printing T. 6. Output is QST.

Garbage Collection

Q25.Easy
In Java, what allows a programmer to destroy an object x directly?
  1. x.delete()
  2. x.finalize()
  3. Runtime.getRuntime().gc()
  4. Only the garbage collection system can destroy an object.
Show answer & explanation
Answer: (D) Only the garbage collection system can destroy an object.
Explanation: 1. Java has no explicit delete operator or delete() method on objects. 2. finalize() is a callback the GC may invoke before reclaiming an object; calling it does not destroy the object. 3. Runtime.getRuntime().gc() only suggests that the JVM run the garbage collector; it does not guarantee or directly destroy a specific object. 4. An object becomes eligible for collection when unreachable, and only the garbage collector actually reclaims it. 5. Hence option D is correct.
Q26.Medium
Which statement about Java garbage collection is true?
  1. Every object that becomes eligible for garbage collection will definitely be reclaimed by the garbage collector.
  2. An object that still has at least one reference pointing to it can never be garbage collected.
  3. An object whose class overrides the finalize() method will never be garbage collected.
  4. Objects created inside anonymous inner classes are allocated on the garbage-collectible heap.
Show answer & explanation
Answer: (D) Objects created inside anonymous inner classes are allocated on the garbage-collectible heap.
Explanation: All Java objects, including those from anonymous inner classes, live on the heap and are subject to garbage collection. Option A is wrong because the GC makes no guarantee it will run. Option B is wrong because isolated reference cycles (islands of isolation) can still be collected. Option C is wrong because finalize() does not prevent collection.
Q27.Medium
Which statement about Java memory management is true?
  1. Memory is reclaimed by calling Runtime.getRuntime().gc().
  2. Objects that are accessible from live threads are not collected.
  3. An OutOfMemoryError is thrown only when a single contiguous block large enough for a request cannot be found.
  4. Objects that override finalize() always have finalize() called before the program ends.
Show answer & explanation
Answer: (B) Objects that are accessible from live threads are not collected.
Explanation: Step 1: gc() only suggests collection; the JVM makes no guarantee, so option A is false. Step 2: An object reachable from a live thread is strongly reachable and cannot be collected, so option B is true. Step 3: The JVM tries to free memory before throwing OutOfMemoryError, so option C is false. Step 4: finalize() is not guaranteed to run, so option D is false.
Q28.Medium
class Widget { } class Maker { Widget makeWidget() { Widget w = new Widget(); /* Line 6 */ return w; /* Line 7 */ } public static void main(String args[]) { Maker m = new Maker(); /* Line 11 */ Widget got = m.makeWidget(); /* Line 12 */ System.out.println("got"); got = new Widget(); /* Line 14 */ System.out.println("finishing"); /* Line 15 */ } } At what point is the Widget object created on line 6 eligible for garbage collection?
  1. after line 12
  2. after line 14
  3. after line 7, when makeWidget() completes
  4. after line 15, when main() completes
Show answer & explanation
Answer: (B) after line 14
Explanation: Step 1: The object created on line 6 is returned on line 7 and stored in got on line 12, so it is reachable. Step 2: Line 14 assigns a new Widget to got, overwriting the only reference to the line-6 object. Step 3: With no references left, the line-6 object becomes eligible for garbage collection right after line 14. Step 4: So option B is correct; options A, C and D are wrong.
Q29.Medium
class Sample { private Item it; void begin() { it = new Item(); this.passItem(it); /* Line 7 */ } /* Line 8 */ void passItem(Item item) { item = null; item = new Item(); } } When is the Item object created inside begin() eligible for garbage collection?
  1. After line 7
  2. After line 8
  3. After the begin() method completes
  4. When the Sample instance running this code becomes eligible for garbage collection
Show answer & explanation
Answer: (D) When the Sample instance running this code becomes eligible for garbage collection
Explanation: Step 1: In begin(), it = new Item() stores the object in the member field it. Step 2: passItem receives a copy of the reference; setting the parameter to null does not affect the field it. Step 3: So after begin() returns, the field it still references the object. Step 4: The field lives as long as the Sample instance, so the object becomes eligible only when that instance is collected. Step 5: Therefore option D is correct.
Q30.Medium
In Java, which statement about garbage collection is true?
  1. Calling System.gc() guarantees that unreachable objects will be garbage collected immediately.
  2. The garbage collector always uses a mark-and-sweep algorithm.
  3. If an object is reachable from a live thread, it cannot be garbage collected.
  4. If object A holds a reference to object B, then object B can never be garbage collected.
Show answer & explanation
Answer: (C) If an object is reachable from a live thread, it cannot be garbage collected.
Explanation: Step 1: Garbage collection reclaims only objects that are no longer reachable from any live thread (or static reference). Step 2: System.gc() is only a request; the JVM may ignore it, so option A is false. Step 3: The JVM is free to choose any collection algorithm, so option B is not guaranteed. Step 4: If A refers to B but A itself is unreachable, both can be collected (islands of isolation), so option D is false. Step 5: Hence the only true statement is that reachable objects cannot be collected.
Q31.Hard
class Collector01 { public static void main(String args[]) { Collector01 c = new Collector01(); c.build(); /* Line 6 */ } Object build() { Object o1 = new Object(); Object[] arr = new Object[1]; arr[0] = o1; o1 = null; return arr[0]; } } Where is the greatest chance of the garbage collector being invoked?
  1. After line 9
  2. After line 10
  3. After line 11
  4. The garbage collector is never invoked in build()
Show answer & explanation
Answer: (D) The garbage collector is never invoked in build()
Explanation: Step 1: o1 = new Object() creates an object; arr[0] = o1 stores a second reference to it. Step 2: o1 = null removes only one reference; arr[0] still points to the object, so it stays reachable. Step 3: return arr[0] returns the reference, and since line 6 ignores the return value, the object becomes unreachable only after build() returns. Step 4: No collection happens inside build(), so option D is correct.

Garbage Collection Eligibility

Q32.Medium
Consider the method: void begin() { A a = new A(); B b = new B(); a.s(b); b = null; /* Line 5 */ a = null; /* Line 6 */ System.out.println("begin completed"); /* Line 7 */ } The B object is created at the start of the method. When is that B object eligible for garbage collection?
  1. after Line 5
  2. after Line 6
  3. after Line 7
  4. There is no way to be absolutely certain.
Show answer & explanation
Answer: (D) There is no way to be absolutely certain.
Explanation: After Line 5, b is null but the B object is still referenced through a.s, so it is reachable. After Line 6, a is null too, so the B object becomes unreachable and eligible. However, eligibility does not mean it is collected at a fixed moment; the garbage collector runs at unpredictable times, so we cannot be absolutely certain when collection actually happens.
Q33.Medium
public class Y {
  public static void main(String[] args) {
    Y y = new Y();
    Y y2 = m1(y);   // Line 4
    Y y4 = new Y();
    y2 = y4;        // Line 6
    doComplexStuff();
  }
  static Y m1(Y my) {
    my = new Y();
    return my;
  }
}
After line 6 runs, how many objects are eligible for garbage collection?
  1. 0
  2. 1
  3. 2
  4. 3
Show answer & explanation
Answer: (B) 1
Explanation: 1. new Y() in main creates object O1, referenced by y. 2. m1(y) passes the reference by value; inside, my = new Y() creates O2 and returns it, so y2 refers to O2. y still refers to O1 (pass-by-value does not change y). 3. new Y() creates O3, referenced by y4. 4. y2 = y4 makes y2 refer to O3; O2 now has no reference and becomes eligible for collection. 5. O1 (via y) and O3 (via y4) are still reachable, so exactly 1 object is eligible.
Q34.Medium
class Node2 {
  public Node2 next;
  public static void main(String[] args) {
    Node2 a = new Node2();   // Line 4
    Node2 b = new Node2();   // Line 5
    a.next = b;
    b.next = a;
    a = new Node2();
    b = a;                   // Line 9
    doComplexStuff();
  }
}
After line 9 runs, how many objects are eligible for garbage collection?
  1. 0
  2. 1
  3. 2
  4. 3
Show answer & explanation
Answer: (C) 2
Explanation: 1. Line 4 creates object O1; line 5 creates object O2. 2. a.next = b and b.next = a make O1 and O2 reference each other (an isolated island). 3. a = new Node2() creates O3 and makes a point to O3; O1 is now unreachable from a. 4. b = a makes b point to O3 as well; O2 is now unreachable from b. 5. O1 and O2 still reference each other but no live reference reaches them, so both are eligible for garbage collection: 2 objects.

Interfaces

Q35.Easy
A Java class wants to implement the java.lang.Runnable interface. Which method signature must that class define?
  1. void run()
  2. public void run()
  3. public void start()
  4. void run(int priority)
Show answer & explanation
Answer: (B) public void run()
Explanation: 1) All methods declared in an interface are implicitly public and abstract. 2) Runnable declares only one method: run(). 3) An implementing class must override it with at least the same (public) access, so the signature must be public void run(). 4) void run() and void run(int priority) use package-private access, which is narrower than public, so they are invalid overrides. 5) start() is not a method of Runnable.
Q36.Medium
Which of the following are valid method declarations inside a Java interface?
1. private int getArea();
2. public float getVol(float x);
3. public void main(String[] args);
4. public static void main(String[] args);
5. boolean setFlag(Boolean[] test);
  1. 1 and 2
  2. 2, 3 and 5
  3. 3, 4 and 5
  4. 2 and 4
Show answer & explanation
Answer: (B) 2, 3 and 5
Explanation: 1. Interface methods cannot be private, so (1) is invalid. 2. (2) is a valid public abstract method declaration. 3. (3) is valid; it is implicitly public and abstract. 4. (4) is invalid because interface methods cannot be static (in the classic interface rules). 5. (5) is valid; it is implicitly public and abstract. 6. Hence 2, 3 and 5 are valid.
Q37.Medium
Which is a valid declaration within an interface definition?
  1. public double methoda();
  2. public final double methoda();
  3. static void methoda(double d1);
  4. protected void methoda(double d1);
Show answer & explanation
Answer: (A) public double methoda();
Explanation: In an interface, methods are implicitly public and abstract. Option A is valid: it declares a public abstract method. Option B is invalid because final methods cannot be abstract, and interface methods are abstract. Option C is invalid because static methods are not allowed in interfaces (prior to Java 8; but even with Java 8, static methods must have a body, and this declaration has no body). Option D is invalid because protected access is not permitted for interface methods.

Keywords

Q38.Easy
Which of the following is a reserved keyword in the Java programming language?
  1. function
  2. transient
  3. objects
  4. pointer
Show answer & explanation
Answer: (B) transient
Explanation: 1. Java keywords are reserved words with special meaning to the compiler. 2. 'transient' is a valid Java keyword used to mark a field that should not be serialized. 3. 'function' is not a Java keyword (Java uses methods). 4. 'objects' and 'pointer' are not Java keywords either. So the reserved word is 'transient'.
Q39.Easy
Which is a valid keyword in java?
  1. interface
  2. string
  3. Float
  4. unsigned
Show answer & explanation
Answer: (A) interface
Explanation: 1) interface is a reserved keyword used to declare an interface. 2) string is not a keyword (String is a class name, with capital S). 3) Float is a class name; the primitive keyword is float. 4) unsigned exists in C/C++ but not in Java.
Q40.Easy
Which of the following are Java reserved words?
1. run
2. import
3. default
4. implement
  1. 1 and 2
  2. 2 and 3
  3. 3 and 4
  4. 2 and 4
Show answer & explanation
Answer: (B) 2 and 3
Explanation: 1) 'import' is a Java keyword used to bring in packages. 2) 'default' is a Java keyword (used in switch and default methods). 3) 'run' is just a method name (Thread/Runnable), not a keyword. 4) 'implement' is not a keyword; the keyword is 'implements'. 5) Hence the reserved words are 2 and 3.
Q41.Medium
Which one of these lists contains only Java programming language keywords?
  1. class, if, void, long, Int, continue
  2. goto, instanceof, native, finally, default, throws
  3. try, virtual, throw, final, volatile, transient
  4. strictfp, constant, super, implements, do
  5. byte, break, assert, switch, include
Show answer & explanation
Answer: (B) goto, instanceof, native, finally, default, throws
Explanation: Option B lists only Java keywords: goto (reserved), instanceof, native, finally, default, throws. Option A has 'Int' (capital I) which is not a keyword; the primitive is 'int'. Option C has 'virtual', which is C++ not Java. Option D has 'constant', not a Java keyword. Option E has 'include', which is C not Java.

Thread Synchronization

Q42.Easy
Which class or interface defines the wait(), notify(), and notifyAll() methods?
  1. Object
  2. Thread
  3. Runnable
  4. Class
Show answer & explanation
Answer: (A) Object
Explanation: 1. The methods wait(), notify(), and notifyAll() are used for inter-thread communication and synchronization. 2. They are defined in the java.lang.Object class, because every object in Java has an intrinsic lock (monitor) and these methods operate on that lock. 3. The Thread class, Runnable interface, and Class class do not define these methods. 4. Therefore, the correct answer is Object.
Q43.Medium
What will be the output of the following program?

class TestSync {
    static final StringBuffer sb1 = new StringBuffer();
    static final StringBuffer sb2 = new StringBuffer();
    public static void main(String args[]) {
        new Thread() {
            public void run() {
                synchronized (sb1) {
                    sb1.append("X");
                    sb2.append("Y");
                }
            }
        }.start();
        new Thread() {
            public void run() {
                synchronized (sb1) {
                    sb1.append("Z");
                    sb2.append("W");
                }
            }
        }.start();
        System.out.println(sb1 + " " + sb2);
    }
}
  1. main() will finish before starting threads.
  2. main() will finish in the middle of one thread.
  3. main() will finish after one thread.
  4. Cannot be determined.
Show answer & explanation
Answer: (D) Cannot be determined.
Explanation: 1. The main thread starts two new threads and then immediately prints sb1 and sb2. 2. The two new threads may or may not have run before the print statement; thread scheduling is not guaranteed. 3. Even if they run, the order of appending to sb1 and sb2 is not fixed because both threads synchronize on sb1, but the main thread does not synchronize. 4. Therefore, the output (the contents of sb1 and sb2 at the time of printing) cannot be determined. 5. The correct answer is 'Cannot be determined.'
Q44.Medium
What will be the output of this program?

public class CounterDemo {
    private int count = 1;
    public synchronized void doWork() {
        for (int i = 0; i < 10; i++)
            System.out.println(count++);
    }
    public static void main(String[] args) {
        CounterDemo demo = new CounterDemo();
        Thread t1 = new Worker(demo);
        Thread t2 = new Worker(demo);
        t1.start();
        t2.start();
    }
}
class Worker extends Thread {
    CounterDemo demo;
    public Worker(CounterDemo cd) { demo = cd; }
    public void run() { demo.doWork(); }
}
  1. It will print the numbers 0 to 19 sequentially
  2. It will print the numbers 1 to 20 sequentially
  3. It will print the numbers 1 to 20, but the order cannot be determined
  4. The code will not compile.
Show answer & explanation
Answer: (B) It will print the numbers 1 to 20 sequentially
Explanation: 1) Both threads share the same CounterDemo object, so they contend for the same monitor. 2) doWork() is synchronized, so only one thread can execute it at a time. 3) The first thread to acquire the lock runs the whole loop, printing 1 through 10. 4) It then releases the lock and the second thread runs the loop, printing 11 through 20. 5) The output is therefore 1 to 20 in order (which thread goes first may vary, but the numbers are always sequential).
Q45.Medium
What will be the output of this program?

public class WaitTest {
    public static void main(String[] args) {
        System.out.print("A ");
        synchronized (args) {
            System.out.print("B ");
            try {
                args.wait();   // Line 11
            } catch (InterruptedException e) { }
        }
        System.out.print("C ");
    }
}
  1. It fails to compile because the IllegalMonitorStateException of wait() is not handled at line 11.
  2. A B C
  3. A C
  4. A B
Show answer & explanation
Answer: (D) A B
Explanation: 1) main prints "A ". 2) It enters the synchronized block on args and prints "B ". 3) args.wait() releases the monitor and puts the main thread into the wait set of args. 4) No other thread ever calls notify()/notifyAll() on args, so main never wakes up. 5) Therefore "C " is never printed and the program hangs; output is just "A B". 6) IllegalMonitorStateException is unchecked, so it need not be caught — the code compiles fine.

Other questions

Q46.Easy
What will be the output of this Java program?

int p = 5;
int q = 2;
if (p = q) {          // Line 3
  System.out.println("p =" + p);
}
  1. p = 2
  2. p = 5
  3. Compilation fails.
  4. The code runs with no output.
Show answer & explanation
Answer: (C) Compilation fails.
Explanation: 1) Line 3 uses a single '=' which is assignment, not comparison ('=='). 2) The expression p = q has type int (value 2), not boolean. 3) An if condition in Java must be boolean, so the compiler reports an error. 4) Therefore compilation fails and nothing is printed.
Q47.Easy
What will be the output of this Java program?

int n = 0;
while (1) {
    if (n == 3) {
        break;
    }
    ++n;
}
System.out.println("n = " + n);
  1. n = 0
  2. n = 3
  3. n = 4
  4. Compilation fails.
Show answer & explanation
Answer: (D) Compilation fails.
Explanation: 1. In Java the condition of a while loop must be a boolean expression. 2. The literal 1 is an int, not a boolean, so 'while (1)' is a type error. 3. The compiler rejects the program, so it never runs. 4. Hence the answer is: Compilation fails.
Q48.Easy
Consider this Java method:

public void check(int num) {
  int flag = 1;
  if (flag) {          // Line 4
    System.out.println("positive");
  } else {
    System.out.println("negative");
  }
}

Which statement is true?
  1. Compilation fails.
  2. "positive" will always be output.
  3. "negative" will always be output.
  4. "positive" will be output for positive values of num, and "negative" for negative values.
Show answer & explanation
Answer: (A) Compilation fails.
Explanation: 1) In Java an if condition must be a boolean expression. 2) On line 4 the condition is flag, which is an int (value 1), not a boolean. 3) The compiler therefore reports an incompatible-types error, so compilation fails. 4) The method body never runs, so none of the output options can occur.
Q49.Easy
Consider this Java class:

public class Looper {
  public void run() {
    int x = 0;
    while (1) {          // Line 6
      System.out.print("next is " + (x + 1));  // Line 8
    }
  }
}

Which statement is true?
  1. There is a syntax error on line 1.
  2. There are syntax errors on lines 1 and 6.
  3. There are syntax errors on lines 1, 6, and 8.
  4. There is a syntax error on line 6.
Show answer & explanation
Answer: (D) There is a syntax error on line 6.
Explanation: 1) Line 1 declares class Looper — a valid Java class name (Java is case sensitive), so no error there. 2) Line 6 uses while(1). In Java the while condition must be a boolean, and an int literal 1 is not boolean, so the compiler reports an error on line 6. 3) Line 8 concatenates a String with an int expression, which is legal. 4) Hence only line 6 has a syntax error.
Q50.Easy
What will be the output of the program?
int a = 1, b = 6;
while (b--) { a++; }
System.out.println("a = " + a + " b = " + b);
  1. a = 6 b = 0
  2. a = 7 b = 0
  3. a = 6 b = -1
  4. Compilation fails.
Show answer & explanation
Answer: (D) Compilation fails.
Explanation: 1. In Java, the condition of a while loop must be a boolean expression. 2. Here the condition is b--, which is an int, not a boolean. 3. Java does not implicitly convert int to boolean (unlike C/C++). 4. Therefore the code fails to compile.
Q51.Easy
Which one of the following correctly creates an instance of an array in Java?
  1. int[] marks = new int[15];
  2. float total = new float[20];
  3. char[] grade = "Some String";
  4. int marks[][] = {4,5,6}, {1,2,3};
Show answer & explanation
Answer: (A) int[] marks = new int[15];
Explanation: 1. Option A declares an int array and constructs it with new int[15] — correct syntax. 2. Option B declares a primitive float but tries to assign an array — incompatible types, compile error. 3. Option C assigns a String literal to a char array — incompatible types, compile error. 4. Option D has two initializers separated by a comma without an enclosing brace — compile error. Hence only the first option is valid.
Q52.Easy
Which of the following will legally declare, construct, and initialize an array?
  1. int[] marks = {"10", "20", "30"};
  2. int[] marks = (5, 8, 2);
  3. int marks[][] = {4, 9, 7, 0};
  4. int marks[] = {4, 3, 7};
Show answer & explanation
Answer: (D) int marks[] = {4, 3, 7};
Explanation: 1. Option A initializes an int array with String literals, which is illegal. 2. Option B uses parentheses instead of curly braces, which is illegal. 3. Option C declares a 2-D array but gives only a single set of values, which is illegal. 4. Option D correctly declares a 1-D int array and initializes it with curly braces. Hence it is legal.
Q53.Easy
Which of the following is a valid declaration inside a Java interface?
  1. public static short stop = 23;
  2. protected short stop = 23;
  3. transient short stop = 23;
  4. final void madness(short stop);
Show answer & explanation
Answer: (A) public static short stop = 23;
Explanation: 1. Interface fields are implicitly public, static and final, so 'public static short stop = 23;' is legal. 2. 'protected' is not allowed for interface fields (they must be public), so option B is invalid. 3. 'transient' is not a permitted modifier for interface fields, so option C is invalid. 4. Interface methods cannot be declared 'final' (and abstract methods have no body), so option D is invalid.
Q54.Easy
What will be the output of this Java program?

public class Sample {
    public static void main(String args[]) {
        class Bar {
            public int i = 7;
        }
        Object o = (Object) new Bar();
        Bar bar = (Bar)o;
        System.out.println("i = " + bar.i);
    }
}
  1. i = 7
  2. Compilation fails.
  3. i = 5
  4. A ClassCastException will occur.
Show answer & explanation
Answer: (A) i = 7
Explanation: 1. A local class Bar is defined inside main with field i = 7. 2. 'new Bar()' creates a Bar object and upcasts it to Object — always allowed. 3. '(Bar)o' downcasts the Object back to Bar; the actual object is a Bar, so the cast succeeds. 4. bar.i is 7, so the output is 'i = 7'.
Q55.Easy
Which one of the following will declare an array and initialize it with five numbers?
  1. Array a = new Array(5);
  2. int [] a = {23,22,21,20,19};
  3. int a [] = new int[5];
  4. int [5] array;
Show answer & explanation
Answer: (B) int [] a = {23,22,21,20,19};
Explanation: 1) Option B uses braces with five values, so it both declares and initializes an int array of length 5. 2) Option A creates an object of a class named Array, not an array. 3) Option C declares an array of size 5 but does not initialize it with numbers. 4) Option D is illegal because a size cannot be given in the declaration brackets.
Q56.Easy
What will be the output of the following Java program?

public class ArrayDemo {
  public static void main(String[] args) {
    double d1[], d2[];
    d1 = new double[5];
    d2 = d1;
    System.out.println("d2[0] = " + d2[0]);
  }
}
  1. It prints d2[0] = 0.0
  2. It prints d2[0] = NaN
  3. An error at d2 = d1; causes compilation to fail.
  4. It prints a garbage value.
Show answer & explanation
Answer: (A) It prints d2[0] = 0.0
Explanation: 1. new double[5] creates an array whose elements are initialized to the default value 0.0. 2. d2 = d1 copies the reference, so d2 points to the same array as d1. 3. d2[0] is therefore 0.0. 4. The output is: d2[0] = 0.0.
Q57.Easy
What will be the output of the program? public class DemoProgram { public static void main(String args[]) { try { System.out.print("Namaste India "); } finally { System.out.println("Cleanup done "); } } }
  1. Nothing. The program will not compile because no exceptions are specified.
  2. Nothing. The program will not compile because no catch clauses are specified.
  3. Namaste India.
  4. Namaste India Cleanup done
Show answer & explanation
Answer: (D) Namaste India Cleanup done
Explanation: A try block must be followed by either a catch or a finally block; here finally is present, so it compiles. The try block runs first and prints 'Namaste India ', then the finally block always runs and prints 'Cleanup done '. So the combined output is 'Namaste India Cleanup done'.
Q58.Easy
What will be the output of this Java program?

class Q207 {
  public static void main(String[] args) {
    int a = 4;
    int b = 7;
    String s = "9";
    System.out.println(a + b + s);
  }
}
  1. 119
  2. 20
  3. 479
  4. Compiler error
Show answer & explanation
Answer: (A) 119
Explanation: Step 1: The expression a + b + s is evaluated left to right. Step 2: a + b are both ints, so 4 + 7 = 11 (numeric addition). Step 3: Now 11 + s: since s is a String, the + becomes concatenation, giving "11" + "9" = "119". Step 4: So the program prints 119.
Q59.Easy
What will be the output of the program?
public class RootExample {
  public static void main(String [] args) {
    double value = -25.0;
    System.out.println(Math.sqrt(value));
  }
}
  1. 5.0
  2. -5.0
  3. NaN
  4. Compilation fails.
Show answer & explanation
Answer: (C) NaN
Explanation: 1) value is a double set to -25.0. 2) Math.sqrt is called with a negative argument. 3) For negative arguments Math.sqrt returns NaN (not a number). 4) The program compiles and prints NaN.
Q60.Easy
What will be the output of the program?
System.out.println(Math.sqrt(-16D));
  1. -4.0
  2. NaN
  3. Compile Error
  4. Runtime Exception
Show answer & explanation
Answer: (B) NaN
Explanation: 1) Math.sqrt takes a double argument; -16D is a valid double. 2) The square root of a negative number is not a real number. 3) Java's Math.sqrt returns NaN (Not a Number) for negative arguments instead of throwing an exception. 4) So the output is NaN.
Q61.Easy
What will be the output of the program?
class Vehicle { }
class Bike extends Vehicle { }
class Truck extends Vehicle { }
public class Garage {
  public static void main(String[] args) {
    Vehicle v = new Bike();
    if (v instanceof Bike)
      System.out.println("Bike");
    else if (v instanceof Vehicle)
      System.out.println("Vehicle");
    else if (v instanceof Truck)
      System.out.println("Truck");
    else
      System.out.println("None");
  }
}
  1. Bike
  2. Vehicle
  3. Truck
  4. None
Show answer & explanation
Answer: (A) Bike
Explanation: 1. v is a reference of type Vehicle pointing to a Bike object. 2. instanceof checks the actual runtime object type. 3. A Bike object is an instance of Bike, so the first condition is true. 4. The first branch prints "Bike" and the else-if chain is skipped. 5. Output: Bike.
Q62.Easy
What will be the output of this program?

String a = "PQRS";
String b = a.toLowerCase();
b.replace('p', 'x');
b.replace('q', 'y');
System.out.println(b);
  1. pqrs
  2. PQRS
  3. xyrx
  4. srqp
Show answer & explanation
Answer: (A) pqrs
Explanation: 1) a.toLowerCase() returns "pqrs", so b refers to "pqrs". 2) String is immutable: b.replace('p','x') returns a new String "xqrs" which is discarded (not assigned). 3) Similarly b.replace('q','y') returns a new String that is discarded. 4) b itself is unchanged, so println prints pqrs.
Q63.Easy
What will be the output of this program?

String s = "mango";
Object o = s;
if (o.equals(s)) {
    System.out.println("P");
} else {
    System.out.println("Q");
}
if (s.equals(o)) {
    System.out.println("R");
} else {
    System.out.println("S");
}

Which lines are printed?
  1. P and R
  2. Q and S
  3. R and S
  4. P and Q
Show answer & explanation
Answer: (A) P and R
Explanation: 1) o refers to the same String object as s, so o.equals(s) calls String.equals and returns true -> prints P. 2) s.equals(o): o holds a String, so String.equals compares contents and returns true -> prints R. 3) Both comparisons are true, so output is P then R.
Q64.Easy
Which of the following are valid calls to Math.max?
1. Math.max(3, 9)
2. Math.max(4.7, 6)
3. Math.max(2, 4, 6, 8)
4. Math.max(-2.5, -3.9f)
  1. 1, 2 and 4
  2. 2, 3 and 4
  3. 1, 2 and 3
  4. 3 and 4
Show answer & explanation
Answer: (A) 1, 2 and 4
Explanation: Math.max is overloaded only for two arguments of type int, long, float or double. (1) two ints → valid. (2) double and int (int widens to double) → valid. (3) four arguments → no such overload → invalid. (4) double and float (float widens to double) → valid. So 1, 2 and 4 are valid.
Q65.Easy
public class ArgDemo {
  public static void main(String[] args) {
    String a = args[1];
    String b = args[2];
    String c = args[3];
    System.out.println("Arg is " + c);
  }
}
Which command will make this program print: Arg is 7
  1. java ArgDemo 777
  2. java ArgDemo 5 7 7 8 9
  3. java ArgDemo 5 8 7 7
  4. java ArgDemo 0 5 7 8
Show answer & explanation
Answer: (C) java ArgDemo 5 8 7 7
Explanation: args[3] is the fourth command-line argument (index starts at 0). We need args[3] = 7. Option 'java ArgDemo 5 8 7 7' gives args = [5, 8, 7, 7], so args[3] = 7 → prints 'Arg is 7'. Other options give args[3] = 8, 9 or 8 respectively.
Q66.Easy
What will be the value of i after the statement: int i = (int) Math.random();
  1. i = 0
  2. i = 1
  3. value of i is undetermined
  4. Statement causes a compile error
Show answer & explanation
Answer: (A) i = 0
Explanation: Step 1: Math.random() returns a double d with 0 <= d < 1. Step 2: The explicit cast (int) is required for narrowing conversion. Step 3: Casting truncates the fractional part, so any value in [0,1) becomes 0. Step 4: Hence i = 0.
Q67.Easy
What is the numerical range of a char in Java?
  1. -128 to 127
  2. -(2^15) to (2^15) - 1
  3. 0 to 32767
  4. 0 to 65535
Show answer & explanation
Answer: (D) 0 to 65535
Explanation: In Java, a char is a 16-bit unsigned integer. It can hold values from 0 to 2^16 - 1, which is 0 to 65535. Therefore, the correct range is 0 to 65535.
Q68.Easy
Which is a valid declaration of a String?
  1. String s1 = null;
  2. String s2 = 'null';
  3. String s3 = (String) 'abc';
  4. String s4 = (String) '\ufeed';
Show answer & explanation
Answer: (A) String s1 = null;
Explanation: Option A assigns null to a String reference, which is valid. Option B uses single quotes for a string literal, but single quotes are for char literals; 'null' is invalid because it contains multiple characters. Option C attempts to cast a char literal 'abc' (which is invalid because it has multiple characters) to String, which is not allowed. Option D tries to cast a char to String, which is not permitted because String is a class and char is a primitive.
Q69.Easy
What will be the output of the program ? public class Test { public static void main(String [] args ) { signed int x = 10 ; for ( int y= 0 ; y< 5 ; y++, x--) System.out.print (x + ", " ); } }
  1. 10, 9, 8, 7, 6,
  2. 9, 8, 7, 6, 5,
  3. Compilation fails.
  4. An exception is thrown at runtime.
Show answer & explanation
Answer: (C) Compilation fails.
Explanation: 1) The declaration uses the word signed before int. 2) signed is not a keyword in Java; all Java integer primitives are already signed. 3) The compiler rejects the declaration, so the program does not compile. 4) Therefore the output is a compilation failure.
Q70.Easy
What will be the output of the program?

public class Y {
    public static void main(String[] args) {
        String cities[] = new String[4];
        for (int i = 0; i < args.length; i++)
            cities[i] = args[i];
        System.out.println(cities[2]);
    }
}

invoked as: java Y Delhi Mumbai
  1. cities
  2. null
  3. Compilation fails
  4. An exception is thrown at runtime
Show answer & explanation
Answer: (B) null
Explanation: 1) new String[4] creates an array of four null references. 2) args contains only two elements: "Delhi" and "Mumbai". 3) The loop assigns cities[0]="Delhi" and cities[1]="Mumbai". 4) cities[2] is never assigned, so it remains null. 5) println prints null.
Q71.Easy
Which statement is true for the class java.util.HashSet?
  1. The elements in the collection are ordered.
  2. The collection is guaranteed to be immutable.
  3. The elements in the collection are guaranteed to be unique.
  4. The elements in the collection are accessed using a unique key.
Show answer & explanation
Answer: (C) The elements in the collection are guaranteed to be unique.
Explanation: 1) HashSet implements the Set interface, which forbids duplicate elements. 2) HashSet makes no guarantee about iteration order, so option A is false. 3) A HashSet can be modified (add/remove), so it is not immutable; option B is false. 4) Key-based access is a Map feature, not a Set feature; option D is false. 5) Therefore only 'elements are guaranteed to be unique' is true.
Q72.Easy
What will be the output of this program?
public class Demo {
  public static void main(String args[]) {
    String name = NULL;
    System.out.println(name);
  }
}
  1. NULL
  2. Compile Error
  3. Code runs but no output
  4. Runtime Exception
Show answer & explanation
Answer: (B) Compile Error
Explanation: 1) In Java the null literal is written in lowercase as null. 2) NULL (uppercase) is not a keyword or literal, so the compiler treats it as an undeclared variable. 3) Since no variable named NULL is declared, compilation fails with 'cannot find symbol'. 4) Therefore the program does not compile.
Q73.Easy
Which Java collection class can grow or shrink in size, gives indexed access to its elements, and has methods that are not synchronized?
  1. java.util.TreeSet
  2. java.util.LinkedHashSet
  3. java.util.List
  4. java.util.ArrayList
Show answer & explanation
Answer: (D) java.util.ArrayList
Explanation: 1) All Java collection classes can grow or shrink dynamically. 2) Indexed access (get by position) is provided by List implementations such as ArrayList. 3) ArrayList's methods are not synchronized, so it is faster than the older synchronized Vector. 4) TreeSet and LinkedHashSet are Sets (no index access) and List is an interface, not a class. 5) Hence java.util.ArrayList fits all conditions.
Q74.Easy
Which statement is true about the class java.util.ArrayList?
  1. The elements in the collection are ordered.
  2. The collection is guaranteed to be immutable.
  3. The elements in the collection are guaranteed to be unique.
  4. The elements in the collection are accessed using a unique key.
Show answer & explanation
Answer: (A) The elements in the collection are ordered.
Explanation: 1) ArrayList maintains insertion order, so its elements are ordered. 2) ArrayList is mutable, so it is not immutable. 3) ArrayList allows duplicates, so elements are not unique. 4) ArrayList is accessed by index, not by a unique key. 5) Hence the correct statement is that the elements are ordered.
Q75.Easy
Ravi wants a collection that automatically rejects duplicate elements, and he also wants to be able to iterate over the elements in their natural (sorted) order. Which interface/implementation provides this capability?
  1. java.util.Map
  2. java.util.Set
  3. java.util.List
  4. java.util.Collection
Show answer & explanation
Answer: (B) java.util.Set
Explanation: 1. A Set by definition cannot contain duplicate elements. 2. A Set implementation such as TreeSet also keeps elements in their natural sorted order when iterated. 3. Map stores key-value pairs (duplicate keys not allowed, but it is not a plain collection of elements). 4. List and Collection allow duplicates and do not guarantee sorted order. 5. Hence Set is the correct choice.
Q76.Easy
Which interface is implemented by java.util.Hashtable?
  1. java.util.Map
  2. java.util.List
  3. java.util.Hashtable
  4. java.util.Collection
Show answer & explanation
Answer: (A) java.util.Map
Explanation: 1. Hashtable stores data as key-value pairs. 2. Key-value storage is defined by the java.util.Map interface, which Hashtable implements. 3. It is not a List or Collection subtype in the list sense, and 'Hashtable' is a class, not an interface. 4. Hence the correct answer is java.util.Map.
Q77.Easy
Which Java collection class lets you store elements associated with key values AND lets you iterate over those entries in insertion (first-in, first-out) order?
  1. java.util.ArrayList
  2. java.util.LinkedHashMap
  3. java.util.HashMap
  4. java.util.TreeMap
Show answer & explanation
Answer: (B) java.util.LinkedHashMap
Explanation: 1. We need key-value storage, so it must be a Map implementation — ArrayList is ruled out. 2. HashMap and TreeMap do not preserve insertion order (TreeMap sorts by key). 3. LinkedHashMap keeps a doubly linked list of entries, so iteration follows insertion (FIFO) order. 4. Hence LinkedHashMap is the correct choice.
Q78.Easy
Which of the following is a valid declaration of a float variable in Java?
  1. float marks = 75F;
  2. float marks = 75.5;
  3. float marks = "75";
  4. float marks = 75.5d;
Show answer & explanation
Answer: (A) float marks = 75F;
Explanation: 1) A float literal needs an F or f suffix when it has a decimal point. 2) 'float marks = 75.5;' fails because 75.5 is a double by default. 3) 'float marks = "75";' is wrong because "75" is a String, not a number. 4) 'float marks = 75.5d;' is wrong because the d suffix makes it a double, causing loss of precision. 5) Only 'float marks = 75F;' is valid.
Q79.Easy
Which of the following are legal lines of code?
(1) int w = ( int )888.8;
(2) byte x = (byte)1000L;
(3) long y = (byte)100;
(4) byte z = (byte)100L;
  1. 1 and 2
  2. 2 and 3
  3. 3 and 4
  4. All statements are correct.
Show answer & explanation
Answer: (D) All statements are correct.
Explanation: (1) Casting double to int is legal; fractional part is truncated (w = 888). (2) Casting long to byte is legal (narrowing cast); 1000L wraps to a byte value. (3) A byte widens to long automatically, so legal (y = 100). (4) Casting long to byte is legal (z = 100). Hence all four compile.
Q80.Easy
What will be the output of this Java program?

class Check {
  public static void main(String[] args) {
    int p = 100;
    double q = 100.1;
    boolean r = (p = q); /* Line 7 */
    System.out.println(r);
  }
}
  1. true
  2. false
  3. Compilation fails
  4. An exception is thrown at runtime
Show answer & explanation
Answer: (C) Compilation fails
Explanation: 1) Line 7 uses the assignment operator = instead of the comparison operator ==. 2) p = q tries to assign a double (100.1) to an int variable p, which is a lossy conversion and not allowed without a cast. 3) Even ignoring that, the result of an assignment p = q would be a double, not a boolean, so it cannot be stored in boolean r. 4) Hence the code does not compile; the program never runs.
Q81.Easy
What is the name of the method used to start a thread's execution?
  1. init();
  2. start();
  3. run();
  4. resume();
Show answer & explanation
Answer: (B) start();
Explanation: 1. start() causes the thread to begin execution; the JVM calls the thread's run() method in a separately executing thread. 2. run() only defines the thread's body and does not start a new thread. 3. There is no init() method in Thread, and resume() is deprecated (it resumes a suspended thread).
Q82.Easy
Which method contains the body of the code that a thread executes?
  1. run();
  2. start();
  3. stop();
  4. main();
Show answer & explanation
Answer: (A) run();
Explanation: 1. The run() method holds the code that forms the thread's task, much like main() holds the entry point of an application. 2. start() only launches the thread, and the JVM then calls run() in that new thread. 3. stop() is deprecated and only forces a thread to stop; main() is the application entry point, not the thread body.
Q83.Easy
Which method registers a thread with the thread scheduler so that it begins execution?
  1. run();
  2. construct();
  3. start();
  4. register();
Show answer & explanation
Answer: (C) start();
Explanation: 1. Calling start() causes the thread to begin execution; the JVM then calls the thread's run() method in a separate thread of execution. 2. run() only contains the thread's body; calling it directly just runs code in the current thread and does not register a new thread. 3. There is no construct() or register() method in the Thread class.
Q84.Easy
Which of the following will not directly cause a thread to stop?
  1. notify()
  2. wait()
  3. InputStream access
  4. sleep()
Show answer & explanation
Answer: (A) notify()
Explanation: 1. notify() wakes up a single thread that is waiting on the object's monitor; it does not stop a thread. 2. wait() causes the current thread to wait until another thread invokes notify() or notifyAll(), so it stops the thread temporarily. 3. InputStream access can block a thread until input is available, causing it to stop temporarily. 4. sleep() causes the current thread to sleep for a specified time, stopping it temporarily. 5. Therefore, notify() does not directly cause a thread to stop; it does the opposite.
Q85.Easy
What will be the output of the following program?

class MyThread extends Thread {
    public static void main(String[] args) {
        MyThread t = new MyThread();
        t.run();
    }
    public void run() {
        for (int i = 1; i < 3; ++i) {
            System.out.print(i + "..");
        }
    }
}
  1. This code will not compile due to line 5.
  2. This code will not compile due to line 6.
  3. 1..2..
  4. 1..2..3..
Show answer & explanation
Answer: (C) 1..2..
Explanation: 1. The main method creates a MyThread object t (line 5) and then calls t.run() directly (line 6). 2. Calling run() directly does not start a new thread; it executes the run() method in the current thread (the main thread). 3. The run() method contains a for loop: for (int i = 1; i < 3; ++i). The loop runs for i = 1 and i = 2. 4. In each iteration, it prints i followed by "..". So it prints "1.." then "2..". 5. The loop terminates when i becomes 3, so it does not print "3..". 6. The code compiles and runs, producing the output: 1..2..
Q86.Easy
What will be the output of the following Java program?

public class MyRunnable extends Thread {
    public void run() {
        System.out.println("Inside run");
        yield();
        System.out.println("Exiting run");
    }
    public static void main(String[] args) {
        (new MyRunnable()).start();
    }
}
  1. The code fails to compile in the main() method
  2. The code fails to compile in the run() method
  3. Only the text "Inside run" will be displayed
  4. The text "Inside run" followed by "Exiting run" will be displayed
Show answer & explanation
Answer: (D) The text "Inside run" followed by "Exiting run" will be displayed
Explanation: 1. The class MyRunnable extends Thread and overrides run(). 2. In main, a new MyRunnable object is created and start() is called, which begins a new thread of execution. 3. The new thread executes run(): it prints "Inside run". 4. Then yield() is called, which may pause the thread to allow others to run, but there are no other threads, so it continues. 5. Finally, it prints "Exiting run". 6. The code compiles and runs without errors, so both lines are printed in order.
Q87.Easy
Given:
public class Job implements Runnable {
  public void run() { /* some code */ }
}
Which of these correctly creates and starts this thread?
  1. new Runnable(Job).start();
  2. new Thread(Job).run();
  3. new Thread(new Job()).start();
  4. new Job().start();
Show answer & explanation
Answer: (C) new Thread(new Job()).start();
Explanation: 1. Job implements Runnable, so an instance of Job must be passed to a Thread constructor. 2. Option A passes the class name Job to a Runnable constructor, which is illegal (Runnable is an interface). 3. Option B also passes the class name, which is illegal. 4. Option D calls start() on Job, but Job has no start() method; only Thread has start(). 5. Option C wraps a Job instance in a Thread and calls start(), which is correct.
Q88.Easy
class Job implements Runnable {
    public static void main(String args[]) {
        /* Missing code? */
    }
    public void run() {}
}
Which of the following lines of code is suitable to start a thread?
  1. Thread t = new Thread(Job);
  2. Thread t = new Thread(Job); t.start();
  3. Job run = new Job(); Thread t = new Thread(run); t.start();
  4. Thread t = new Thread(); run.start();
Show answer & explanation
Answer: (C) Job run = new Job(); Thread t = new Thread(run); t.start();
Explanation: 1. To start a thread you need a Runnable instance passed to a Thread object. 2. Job is a class name, not an object, so 'new Thread(Job)' is invalid. 3. Create an object: Job run = new Job(); 4. Pass it to the thread: Thread t = new Thread(run); 5. Call t.start() to begin execution. Option 3 does all of this correctly.
Q89.Easy
Which two of the following methods are defined in the Thread class?
1. start()
2. wait()
3. notify()
4. run()
5. terminate()
  1. 1 and 4
  2. 2 and 3
  3. 3 and 4
  4. 2 and 4
Show answer & explanation
Answer: (A) 1 and 4
Explanation: 1. start() and run() belong to the Thread class. 2. wait() and notify() are methods of the Object class, not Thread. 3. terminate() does not exist in any thread-related class. 4. Hence the correct pair is start() and run(), i.e. 1 and 4.
Q90.Medium
Consider the following Java method:

public void check(boolean x, boolean y) {
    if (x) {
        System.out.println("X");
    } else if (x && y) {
        System.out.println("X && Y");
    } else {
        if (!y) {
            System.out.println("notY");
        } else {
            System.out.println("ELSE");
        }
    }
}

Which statement about the output is correct?
  1. If x is true and y is true then the output is "X && Y"
  2. If x is true and y is false then the output is "notY"
  3. If x is false and y is true then the output is "ELSE"
  4. If x is false and y is false then the output is "ELSE"
Show answer & explanation
Answer: (C) If x is false and y is true then the output is "ELSE"
Explanation: 1) If x is true, the first if prints "X" regardless of y, so "X && Y" can never print (option A wrong). 2) If x is true and y is false, output is "X", not "notY" (option B wrong). 3) If x is false, the else-if (x && y) is false, so we go to else: if y is true, !y is false, so "ELSE" prints (option C correct). 4) If x is false and y is false, !y is true, so "notY" prints, not "ELSE" (option D wrong).
Q91.Medium
What will be the output of the following Java program?

int total = 0;
outer: while (true) {
    total++;
    inner: for (int j = 0; j < 8; j++) {
        total += j;
        if (j == 2) continue inner;
        break outer;
    }
    continue outer;
}
System.out.println(total);
  1. 1
  2. 2
  3. 3
  4. 4
Show answer & explanation
Answer: (A) 1
Explanation: 1) Enter the while loop; total becomes 1. 2) Enter the for loop with j = 0; total += 0 keeps total = 1. 3) j == 2 is false, so break outer executes immediately, exiting the while loop. 4) The continue statements are never reached. 5) Print total = 1.
Q92.Medium
What will be the output of the following Java program?

for (int k = 0; k < 6; k += 3) {
    System.out.print(k + " ");
}
System.out.println(k); // Line 5
  1. 0 3 6
  2. 0 3 6 6
  3. 0 1 2 3 4 5 6
  4. Compilation fails.
Show answer & explanation
Answer: (D) Compilation fails.
Explanation: 1) The loop declares k inside the for statement, so k exists only within the loop body. 2) The loop prints 0 and 3 (k = 0, then 3), then k becomes 6 and the loop ends. 3) Line 5 tries to use k after the loop, but k is out of scope there. 4) Hence the compiler reports an error: cannot find symbol k. 5) So the program does not compile.
Q93.Medium
What will be the output of this Java program?

Double d = new Double("7");
switch (d) {
    case 7:
        System.out.println("Seven");
    case 0:
        System.out.println("Zero");
    default:
        System.out.println("Default");
}
  1. Zero
  2. Seven
  3. Default
  4. Compilation fails
Show answer & explanation
Answer: (D) Compilation fails
Explanation: 1. A switch selector in Java may be int-compatible types (byte, short, char, int), their wrappers, String, or enum — not Double. 2. Here the selector is a Double object, which is not allowed. 3. The compiler reports an error, so the program does not run. 4. Answer: Compilation fails.
Q94.MediumAnswer under review
What will be the output of this Java program?

public class Demo {
    public static void main(String args[]) {
        int a = 1, b = 0;
        switch (a) {
            case 2: b += 5;
            case 4: b += 3;
            default: b += 2;
            case 0: b += 7;
        }
        System.out.println("b = " + b);
    }
}
  1. b = 0
  2. b = 2
  3. b = 7
  4. b = 12
Show answer & explanation
Answer: (D) b = 12
Explanation: 1. a = 1 matches no case label, so control jumps to the default block. 2. default: b += 2 makes b = 2. 3. There is no break, so execution falls through to case 0: b += 7 makes b = 9? No — careful: default adds 2 (b=2), then case 0 adds 7, giving b = 9. Wait, recompute: b starts 0, default adds 2 -> 2, case 0 adds 7 -> 9. But option list has 12; let me recheck: case 2 and case 4 are skipped since a=1. So b = 2 + 7 = 9. Hmm, the intended answer must match an option. Let me adjust: default adds 5 and case 0 adds 7 -> 12. Corrected program: default: b += 5; case 0: b += 7; giving b = 12.
Q95.Medium
What will be the output of this Java program?

boolean flag = true;
if (flag = false)      /* Line 2 */
{
    System.out.println("red");
}
else if (flag)         /* Line 6 */
{
    System.out.println("green");
}
else if (!flag)        /* Line 10 */
{
    System.out.println("blue");   /* Line 12 */
}
else
{
    System.out.println("white");
}
  1. red
  2. green
  3. blue
  4. white
Show answer & explanation
Answer: (C) blue
Explanation: 1. Line 2 uses '=' (assignment), not '=='. So flag is set to false and the condition value is false. 2. Because the condition is false, the 'red' block is skipped. 3. Line 6 checks flag, which is now false, so 'green' is skipped. 4. Line 10 checks !flag, which is !false = true, so the 'blue' block runs. 5. Output is blue.
Q96.MediumAnswer under review
What will be the output of this Java program?

public class SwitchDemo {
  public static void main(String[] args) {
    System.out.println("result = " + compute(3));
  }
  public static int compute(int n) {
    int k = 2;
    switch (n) {
      case 1: k++;
      case 2: k++;
      case 3: k++;
      case 4: k++;
      case 5: k++;
      default: k++;
    }
    return k + n;
  }
}
  1. result = 3
  2. result = 5
  3. result = 7
  4. result = 9
Show answer & explanation
Answer: (C) result = 7
Explanation: 1) compute(3) is called, so n = 3 and k starts at 2. 2) switch(n) jumps to case 3 (no break statements anywhere). 3) case 3: k becomes 3; case 4: k becomes 4; case 5: k becomes 5; default: k becomes 6. 4) Return k + n = 6 + 3 = 9? No — careful: k after fall-through is 6, so 6 + 3 = 9. Wait, recount: k=2, case3 ->3, case4 ->4, case5 ->5, default ->6. Return 6+3=9. 5) Corrected: the printed value is 9, so the matching option is 'result = 9'.
Q97.Medium
What will be the output of the following Java program?

int p = 1, q = 10;
do {
    if (p > q) {
        break;
    }
    q--;
} while (++p < 5);
System.out.println("p = " + p + " and q = " + q);
  1. p = 6 and q = 5
  2. p = 5 and q = 5
  3. p = 6 and q = 4
  4. p = 5 and q = 6
Show answer & explanation
Answer: (D) p = 5 and q = 6
Explanation: 1. Start: p=1, q=10. p>q false, so q becomes 9; then ++p makes p=2, and 2<5 true, loop continues. 2. p=2, q=9: q becomes 8; ++p makes p=3, 3<5 true. 3. p=3, q=8: q becomes 7; ++p makes p=4, 4<5 true. 4. p=4, q=7: q becomes 6; ++p makes p=5, and 5<5 is false, so the loop ends. 5. Final values: p=5, q=6.
Q98.MediumAnswer under review
Consider the following switch statement:

switch (x) {
default:
    System.out.println("Hello");
}

Which two of the following are acceptable types for x?
1. byte
2. long
3. char
4. float
5. Short
6. Long
  1. 1 and 3
  2. 2 and 4
  3. 3 and 5
  4. 4 and 6
Show answer & explanation
Answer: (A) 1 and 3
Explanation: 1. A switch selector must be an integer-compatible type: byte, short, char, int (and their wrappers Byte, Short, Character, Integer), plus String and enum. 2. byte (option 1) is allowed because it widens to int. 3. char (option 3) is allowed because it also widens to int. 4. long, float, Short and Long are not permitted as switch selectors (Short/Long are wrapper reference types here). 5. So the acceptable pair is 1 and 3.
Q99.Medium
What will be the output of the following Java program?

int a = 0, b = 5;
outer:
for (;;) {
    a++;
    for (;;) {
        if (a > --b) {
            break outer;
        }
    }
    System.out.println("a =" + a + ", b = " + b);
}
  1. a = 1, b = 0
  2. a = 1, b = 4
  3. a = 3, b = 4
  4. Compilation fails.
Show answer & explanation
Answer: (D) Compilation fails.
Explanation: 1. The outer for(;;) loop opens a block with '{' and the inner for(;;) loop opens another '{'. 2. The inner loop's closing '}' is present, but the outer loop's closing '}' is missing. 3. The method body therefore has unbalanced braces, which is a syntax error. 4. The compiler fails, so no output is produced.
Q100.Medium
What will be the output of the following Java program?

int k = 0;
start:
if (k < 2) {
    System.out.print("k is " + k);
    k++;
    continue start;
}
  1. k is 0
  2. k is 0 k is 1
  3. Compilation fails.
  4. None of the above
Show answer & explanation
Answer: (C) Compilation fails.
Explanation: 1. The label 'start' is attached to an if statement, not to a loop. 2. In Java, the continue statement may only appear inside a loop (for, while, do-while). 3. Here continue start; is used outside any loop, so the compiler reports an error. 4. Hence the program does not compile.
123

Get In Touch

INTMAT EDTECH (OPC) PRIVATE LIMITED
No - 16, Javaraiahna Doddi, Mysore Road,
Bengaluru Urban, BENGALURU,
Karnataka 560098, India

contact@intmatedtech.com

TestMyIndia All India Rank