MCQ Questions

Question Bank › Technical › Java › MCQ

123

Other questions

Q101.Medium
What will be the output of the following program?
public class Check {
    static boolean f1, f2;
    public static void main(String[] args) {
        int x = 0;
        if (!f1) {
            if (!f2) {
                f1 = true;
                x++;
                if (5 > 6) { x++; }
                if (!f1)
                    x = x + 10;
                else if (f2 = true)
                    x = x + 100;
                else if (f1 | f2)
                    x = x + 1000;
            }
        }
        System.out.println(x);
    }
}
  1. 0
  2. 1
  3. 101
  4. 111
Show answer & explanation
Answer: (C) 101
Explanation: 1. Static booleans f1 and f2 default to false. 2. !f1 is true, so the outer if is entered; !f2 is true, so the inner if is entered. 3. f1 is set to true and x becomes 1. 4. 5 > 6 is false, so x is not incremented again. 5. !f1 is now false, so the first branch is skipped. 6. else if (f2 = true) is an assignment: f2 becomes true and the condition evaluates to true, so x = 1 + 100 = 101. 7. The remaining else-if is skipped; output is 101.
Q102.Medium
What will be the output of the program?
public class Check {
  static boolean flag;
  public static void main(String[] args) {
    short count = 42;
    if (count < 50 && !flag) /* Line 7 */
      count++;
    if (count > 50); /* Line 9 */
    else if (count > 40) {
      count += 7;
      count++;
    }
    else --count;
    System.out.println(count);
  }
}
  1. 41
  2. 42
  3. 50
  4. 51
Show answer & explanation
Answer: (D) 51
Explanation: 1. Static boolean flag defaults to false, so !flag is true; count < 50 is true, so count++ makes count = 43. 2. Line 9: if (count > 50); is a valid empty statement — the condition is false (43 > 50 is false), so its empty body is skipped. 3. The else-if (count > 40) is true (43 > 40), so count += 7 gives 50, then count++ gives 51. 4. Output is 51.
Q103.Medium
What will be the output of the program?
public class Demo {
  public static void main(String[] args) {
    int k = 1;
    do while (k < 1)
      System.out.print("k is " + k);
    while (k > 1);
  }
}
  1. k is 1
  2. k is 1 k is 1
  3. No output is produced.
  4. Compilation error
Show answer & explanation
Answer: (C) No output is produced.
Explanation: 1. The outer loop is a do-while; its body is the single statement: a while loop. 2. The inner while condition (k < 1) is false since k = 1, so the inner loop body never runs. 3. The do-while condition (k > 1) is also false, so the do-while ends after one iteration. 4. Nothing is printed, so no output is produced.
Q104.Medium
Which of the following declarations are valid in Java?
1. class ShapeCalc extends AreaCalc { double getArea(int r); }
2. interface ShapeCalc implements ExtraMath { double getVol(int x, int y); }
3. interface ShapeCalc extends AreaCalc { float getAvg(int h, int l); }
4. class ShapeCalc implements ExtraMath { double getArea(int rad); }
5. abstract class ShapeCalc implements AreaCalc, ExtraMath { public double getArea(int rad) { return rad * rad * 3.14; } }
  1. 1 only
  2. 2 only
  3. 3 and 5
  4. 1 and 4
Show answer & explanation
Answer: (C) 3 and 5
Explanation: 1. A class cannot extend an interface, so 1 is invalid. 2. An interface cannot implement another interface, so 2 is invalid. 3. An interface may extend another interface without implementing its methods, so 3 is valid. 4. Class ShapeCalc implements ExtraMath but declares getArea (from AreaCalc), not getVol, so 4 is invalid. 5. An abstract class need not implement all interface methods, and getArea is correctly implemented, so 5 is valid. Hence 3 and 5 are correct.
Q105.Medium
Given:

interface Shape { boolean visible(); byte size(short s); }

Which two code fragments will compile?
1. interface Shape2 implements Shape {}
2. abstract class Shape2 extends Shape { public boolean visible(){ return true; } }
3. abstract class Shape2 implements Shape {}
4. abstract class Shape2 implements Shape { public boolean visible(){ return (9 > 4); } }
5. abstract class Shape2 implements Shape { protected boolean visible(){ return (5 > 7); } }
  1. 1 and 2
  2. 2 and 3
  3. 3 and 4
  4. 1 and 5
Show answer & explanation
Answer: (C) 3 and 4
Explanation: 1. Fragment 1 fails: an interface cannot 'implement' another interface (it must extend). 2. Fragment 2 fails: a class cannot 'extend' an interface. 3. Fragment 3 compiles: an abstract class need not implement any interface methods. 4. Fragment 4 compiles: visible() is implemented as public and returns a boolean. 5. Fragment 5 fails: interface methods are implicitly public, so a protected implementation is illegal. 6. Hence only 3 and 4 compile.
Q106.Medium
What will be the output of the following program?
class Base {
    public Integer getSize() { return new Integer(4); }
}
public class Derived extends Base {
    public Long getSize() { return new Long(5); }
    public static void main(String[] args) {
        Base b = new Base();
        Derived d = new Derived();
        System.out.println(b.getSize().toString() + "," + d.getSize().toString());
    }
}
  1. 4, 4
  2. 4, 5
  3. 5, 4
  4. Compilation fails.
Show answer & explanation
Answer: (D) Compilation fails.
Explanation: 1. In the superclass, getSize() returns Integer. 2. In the subclass, getSize() returns Long. 3. For a valid override, the return type must be the same or a covariant (subtype) of the superclass return type. 4. Long is not a subtype of Integer, so this is not a valid override. 5. It is also not an overload because the parameter list is unchanged. 6. Therefore the compiler reports an error and compilation fails.
Q107.Medium
In Java, which two of the following are legal declarations for non-nested classes and interfaces?
1. final abstract class Vehicle {}
2. public static interface Vehicle {}
3. final public class Vehicle {}
4. protected abstract class Vehicle {}
5. protected interface Vehicle {}
6. abstract public class Vehicle {}
  1. 1 and 4
  2. 2 and 5
  3. 3 and 6
  4. 4 and 6
Show answer & explanation
Answer: (C) 3 and 6
Explanation: 1. A class cannot be both final and abstract, so (1) is illegal. 2. Top-level interfaces and classes cannot be marked static, so (2) is illegal. 3. (3) final public class is legal (modifier order does not matter). 4. Top-level classes cannot be protected, so (4) is illegal. 5. Top-level interfaces cannot be protected, so (5) is illegal. 6. (6) abstract public class is legal. So the legal ones are (3) and (6).
Q108.Medium
Which of the following class-level (non-local) variable declarations will NOT compile?
  1. protected int a;
  2. transient int b = 3;
  3. private synchronized int e;
  4. volatile int d;
Show answer & explanation
Answer: (C) private synchronized int e;
Explanation: 1. 'protected int a;' is legal: protected is a valid access modifier for fields. 2. 'transient int b = 3;' is legal: transient is a valid field modifier. 3. 'private synchronized int e;' is illegal because 'synchronized' applies only to methods (and blocks), not to variables. 4. 'volatile int d;' is legal: volatile is a valid field modifier.
Q109.Medium
Which two of the following array declarations cause a compiler error?
1. float[] f = new float(3);
2. float f2[] = new float[];
3. float[] f1 = new float[3];
4. float f3[] = new float[3];
5. float f5[] = {1.0f, 2.0f, 2.0f};
  1. 2, 4
  2. 3, 5
  3. 4, 5
  4. 1, 2
Show answer & explanation
Answer: (D) 1, 2
Explanation: 1. Declaration 1 uses parentheses 'new float(3)' instead of brackets, causing a compiler error. 2. Declaration 2 uses 'new float[]' without a size and without an initializer, causing a compiler error. 3. Declaration 3 is valid: 'new float[3]' creates an array of size 3. 4. Declaration 4 is valid: 'float f3[] = new float[3];' is legal C-style array syntax. 5. Declaration 5 is valid: array initializer with three float literals. 6. Hence the errors are in 1 and 2.
Q110.Medium
Consider the following Java code:

public class Shop {
    public void billingCounter() {
        // Line 5
    }
    public class Counter {
    }
    public static void main(String[] args) {
        Shop s = new Shop();
        // Line 10
    }
}

Which of the following code fragments, when inserted at the indicated line, will allow the program to compile?
  1. new Counter(); // At line 5
  2. new Counter(); // At line 10
  3. new s.Counter(); // At line 10
  4. new Shop.Counter(); // At line 10
Show answer & explanation
Answer: (A) new Counter(); // At line 5
Explanation: 1. Counter is a non-static inner class of Shop, so it can only be created inside an instance context of Shop. 2. Line 5 is inside the instance method billingCounter(), so 'new Counter();' is valid there (implicitly uses this). 3. Line 10 is inside static main(), so 'new Counter();' fails (non-static class cannot be referenced from static context). 4. 'new s.Counter();' is invalid syntax; correct form would be s.new Counter(). 5. 'new Shop.Counter();' fails because Counter is non-static and cannot be created via the class name in a static context.
Q111.Medium
Which two statements are true for any concrete class implementing the java.lang.Runnable interface?
1. You can extend the Runnable interface as long as you override the public run() method.
2. The class must contain a method called run() from which all code for that thread will be initiated.
3. The class must contain an empty public void method named run().
4. The class must contain a public void method named runnable().
5. The class definition must include the words implements Threads and contain a method called run().
6. The mandatory method must be public, with a return type of void, must be called run(), and cannot take any arguments.
  1. 1 and 3
  2. 2 and 4
  3. 1 and 5
  4. 2 and 6
Show answer & explanation
Answer: (D) 2 and 6
Explanation: 1. A concrete class implementing Runnable must provide run(); that method holds the thread's code — statement 2 is true. 2. The signature must be exactly public void run() with no parameters — statement 6 is true. 3. Statement 1 is false: a class cannot extend an interface. 4. Statement 3 is false: run() need not be empty. 5. Statement 4 is false: the method is run(), not runnable(). 6. Statement 5 is false: the interface is Runnable, not Threads.
Q112.Medium
/* Missing statements ? */
public class NewTreeSet extends java.util.TreeSet {
    public static void main(String[] args) {
        java.util.TreeSet t = new java.util.TreeSet();
        t.clear();
    }
    public void clear() {
        TreeMap m = new TreeMap();
        m.clear();
    }
}

Which two statements, added independently at the beginning of the program, allow the code to compile?
1. No statement is required
2. import java.util.*;
3. import.java.util.Tree*;
4. import java.util.TreeSet;
5. import java.util.TreeMap;
  1. 1 only
  2. 2 and 5
  3. 3 and 4
  4. 3 and 5
Show answer & explanation
Answer: (B) 2 and 5
Explanation: 1. TreeSet is always written with its fully qualified name, so it needs no import. 2. TreeMap is used by its simple name, so it must be imported. 3. Statement 2 (import java.util.*;) imports TreeMap — works. 4. Statement 5 (import java.util.TreeMap;) imports TreeMap — works. 5. Statement 1 fails (TreeMap not imported), statement 3 is invalid syntax, statement 4 imports only TreeSet. 6. So the correct pair is 2 and 5.
Q113.Medium
Consider the following program:

public class Demo {
    public static void main(String[] args) throws Exception {
        java.io.PrintWriter out = new java.io.PrintWriter(System.out);
        out.println("Namaste");
        out.flush();
    }
}

What line of code, if any, must be added at the top to make this program compile?
  1. No statement required.
  2. import java.io.*;
  3. include java.io.*;
  4. import java.io.PrintWriter;
Show answer & explanation
Answer: (A) No statement required.
Explanation: 1) The program refers to PrintWriter using its fully qualified name java.io.PrintWriter. 2) When a class is referenced by its fully qualified name, no import is needed. 3) The constructor used, PrintWriter(OutputStream), exists, so the code compiles as written. 4) Therefore no statement is required.
Q114.Medium
What will be the output of this Java program?

public class Box {
    void Box() /* Line 3 */ {
        System.out.println("Inside Box");
    }
    public static void main(String[] args) {
        new Box();
    }
}
  1. Inside Box
  2. Compilation fails.
  3. An exception is thrown at line 3.
  4. The code executes with no output.
Show answer & explanation
Answer: (D) The code executes with no output.
Explanation: 1. A constructor must have the same name as the class AND no return type. 2. Here 'void Box()' has a return type (void), so it is an ordinary method, not a constructor. 3. 'new Box()' calls the implicit default constructor, not the method Box(). 4. The method Box() is never invoked, so nothing is printed.
Q115.Medium
Which three of the following statements about default constructors in Java are true?
1. The default constructor initialises method variables.
2. The default constructor has the same access modifier as its class.
3. The default constructor invokes the no-argument constructor of the superclass.
4. If a class lacks a no-argument constructor, the compiler always creates a default constructor.
5. The compiler creates a default constructor only when there are no other constructors declared in the class.
  1. 1, 2 and 4
  2. 2, 3 and 5
  3. 3, 4 and 5
  4. 1, 2 and 3
Show answer & explanation
Answer: (B) 2, 3 and 5
Explanation: 1) Statement 1 is false: method (local) variables are never initialised by a constructor. 2) Statement 2 is true: the compiler gives the default constructor the same access level as the class. 3) Statement 3 is true: the default constructor simply calls super() — the superclass no-arg constructor. 4) Statement 4 is false: if the class already declares any constructor, no default constructor is added. 5) Statement 5 is true: a default constructor is generated only when no constructor is declared. 6) Hence the true statements are 2, 3 and 5.
Q116.Medium
Which three of the following are correct array declarations in Java?
1. public int marks[]
2. static int[] marks
3. public [] int marks
4. private int marks[3]
5. private int[3] marks[]
6. public final int[] marks
  1. 1, 3, 4
  2. 2, 4, 5
  3. 1, 2, 6
  4. 2, 5, 6
Show answer & explanation
Answer: (C) 1, 2, 6
Explanation: 1) (1) public int marks[] — valid; brackets may follow the variable name. 2) (2) static int[] marks — valid; brackets may follow the type. 3) (3) public [] int marks — invalid; brackets cannot appear before the type in that position. 4) (4) private int marks[3] — invalid; size is not given in a declaration, only at creation with new. 5) (5) private int[3] marks[] — invalid; the 3 inside brackets is not allowed in a declaration. 6) (6) public final int[] marks — valid; modifiers plus type-brackets plus name is fine. 7) So the correct three are 1, 2 and 6.
Q117.Medium
What will be the output of the following program?

class Vehicle {
    public int wheels = 0;
    public Vehicle(String name) {
        wheels = 1;
    }
}

class Car extends Vehicle {
    public Car(String name) {
        wheels = 2;
    }
    public static void main(String args[]) {
        Car c = new Car("Sedan");
        System.out.println(c.wheels);
    }
}
  1. 0
  2. 1
  3. 2
  4. Compilation fails.
Show answer & explanation
Answer: (D) Compilation fails.
Explanation: 1) Vehicle declares only a constructor with a String argument, so no no-argument constructor is created. 2) The Car constructor does not explicitly call super(...), so the compiler inserts an implicit call to super() with no arguments. 3) Since Vehicle has no no-arg constructor, the compiler cannot find super() and reports an error. 4) The fix would be to add super(name); as the first line of the Car constructor. As written, compilation fails.
Q118.Medium
What will be the output of the following program?

public class Demo {
    public int compute() {
        static int count = 0;
        count++;
        return count;
    }
    public static void main(String args[]) {
        Demo d = new Demo();
        d.compute();
        int result = d.compute();
        System.out.println(result);
    }
}
  1. 0
  2. 1
  3. 2
  4. Compilation fails.
Show answer & explanation
Answer: (D) Compilation fails.
Explanation: 1) Inside the method compute(), the variable is declared as static int count = 0;. 2) In Java, local variables declared inside a method cannot have the static modifier; static is only allowed for class members. 3) The compiler reports an error: 'illegal start of expression' at that line. 4) Therefore the program does not compile, so the output is a compilation failure.
Q119.Medium
Consider the Java class declaration: public class Student { }. What is the prototype of the default constructor generated for this class?
  1. Student( )
  2. Student(void)
  3. public Student( )
  4. public Student(void)
Show answer & explanation
Answer: (C) public Student( )
Explanation: 1) The class Student is declared public, so the compiler-generated default constructor takes the same access modifier as the class, i.e. public. 2) A constructor has no return type, so writing void makes it an ordinary method, not a constructor — options with void are wrong. 3) A constructor with no access modifier would be package-private, which does not match the public class. 4) Hence the correct prototype is public Student( ).
Q120.Medium
Which of the following are legal Java method declarations?
1. protected abstract void m1();
2. static final void m1() {}
3. synchronized public final void m1() {}
4. private native void m1();
  1. 1 and 3
  2. 2 and 4
  3. 1 only
  4. All of them are legal declarations.
Show answer & explanation
Answer: (D) All of them are legal declarations.
Explanation: 1) protected abstract void m1(); — legal: abstract methods may be protected and end with a semicolon. 2) static final void m1() {} — legal: static and final can be combined on a method. 3) synchronized public final void m1() {} — legal: modifiers can appear in any order. 4) private native void m1(); — legal: native methods may be private and have no body. 5) Hence all four declarations are legal.
Q121.Medium
What will be the output of the program?

class Vehicle {
    Vehicle() {
        System.out.print("Vehicle");
    }
}

public class Car extends Vehicle {
    public static void main(String[] args) {
        new Car();   /* Line 12 */
        new Vehicle(); /* Line 13 */
    }
}
  1. Vehicle
  2. VehicleVehicle
  3. Compilation fails
  4. The code runs with no output
Show answer & explanation
Answer: (B) VehicleVehicle
Explanation: 1) Car extends Vehicle but defines no constructor, so Java supplies a default Car() constructor. 2) That default constructor implicitly calls super(), i.e. Vehicle(). 3) Line 12 creates a Car, so "Vehicle" is printed once. 4) Line 13 creates a Vehicle directly, printing "Vehicle" again. 5) Total output: VehicleVehicle. The code compiles fine.
Q122.Medium
Which of the following Java statements causes a compiler error?
  1. int[] marks = {45, 60, 75};
  2. int[][] marks = {12, 34, 56}, {78, 90, 11};
  3. String[] cities = {"Pune", "Jaipur", "Kochi"};
  4. boolean[] flags = new boolean[] {true, false, true};
Show answer & explanation
Answer: (B) int[][] marks = {12, 34, 56}, {78, 90, 11};
Explanation: 1) A one-dimensional array with a single initializer list is fine. 2) For a two-dimensional array, each row must be wrapped in its own pair of braces. 3) The statement int[][] marks = {12, 34, 56}, {78, 90, 11}; has two separate initializer lists after the equals sign, so the compiler expects an identifier and reports an error. 4) Correct form: int[][] marks = {{12, 34, 56}, {78, 90, 11}};. 5) The String and boolean array declarations are legal.
Q123.MediumAnswer under review
What will be the output of the following Java program?

import java.util.*;
public class NewTreeSet2 extends NewTreeSet {
  public static void main(String[] args) {
    NewTreeSet2 t = new NewTreeSet2();
    t.count();
  }
}
protected class NewTreeSet {
  void count() {
    for (int x = 0; x < 7; x++, x++) {
      System.out.print(" " + x);
    }
  }
}
  1. 0 2 4
  2. 0 2 4 6
  3. Compilation fails at line 2
  4. Compilation fails at line 10
Show answer & explanation
Answer: (D) Compilation fails at line 10
Explanation: 1. A top-level (non-nested) class cannot be declared protected. 2. The declaration 'protected class NewTreeSet' is therefore illegal. 3. The compiler fails at that line (line 10 in the listing). 4. So the program does not compile.
Q124.Medium
Which of the following are classes that can be thrown using a throw statement in Java?
1. Error
2. Event
3. Object
4. Throwable
5. Exception
6. RuntimeException
  1. 1, 2, 3 and 4
  2. 2, 3, 4 and 5
  3. 1, 4, 5 and 6
  4. 2, 4, 5 and 6
Show answer & explanation
Answer: (C) 1, 4, 5 and 6
Explanation: 1. Only instances of Throwable (or its subclasses) can be thrown. 2. Error is a subclass of Throwable, so it can be thrown. 3. Throwable itself can be thrown. 4. Exception and RuntimeException are subclasses of Throwable, so they can be thrown. 5. Event and Object are not subclasses of Throwable, so they cannot be thrown. 6. Therefore 1, 4, 5 and 6 are correct.
Q125.Medium
Consider this code placed inside a class: System.out.print("Begin "); try { System.out.print("Working"); throw new FileNotFoundException(); } System.out.print(" Middle "); /* Line 7 */ catch (EOFException e) { System.out.print("EOF error"); } catch (FileNotFoundException e) { System.out.print("File missing"); } Given that EOFException and FileNotFoundException are both subclasses of IOException, which statement is most true?
  1. The code will not compile.
  2. Code output: Begin Working File missing.
  3. Code output: Begin Working EOF error.
  4. Code output: Begin Working Middle File missing.
Show answer & explanation
Answer: (A) The code will not compile.
Explanation: 1) After a try block, only catch or finally clauses may appear. 2) Line 7 places a plain statement (System.out.print) between the try block and the catch clauses. 3) This is a syntax error, so compilation fails. 4) If line 7 were removed, the code would compile and print "Begin Working File missing".
Q126.Medium
Which statement is true?
  1. catch(X x) can catch subclasses of X, where X is a subclass of Exception.
  2. The Error class is a subclass of RuntimeException.
  3. Any statement that can throw an Error must be enclosed in a try block.
  4. Any statement that can throw an Exception must be enclosed in a try block.
Show answer & explanation
Answer: (A) catch(X x) can catch subclasses of X, where X is a subclass of Exception.
Explanation: 1) Option 1 is true: a catch clause for a superclass also catches any subclass exception object. 2) Option 2 is false: Error extends Throwable, not RuntimeException. 3) Option 3 is false: Errors are unchecked and need not be caught. 4) Option 4 is false: checked exceptions can be declared with throws and propagated to the caller instead of being caught.
Q127.Medium
What will be the output of the program? public class FlowTest { public static void raise() { System.out.print("raise "); throw new RuntimeException(); } public static void main(String[] args) { try { System.out.print("start "); raise(); } catch (Exception e) { System.out.print("caught "); } finally { System.out.print("finally "); } System.out.println("done"); } }
  1. start raise caught
  2. Compilation fails
  3. start raise RuntimeException caught done
  4. start raise caught finally done
Show answer & explanation
Answer: (D) start raise caught finally done
Explanation: 1) main prints "start " then calls raise(). 2) raise() prints "raise " and throws a RuntimeException. 3) The exception propagates to main's catch block, which prints "caught ". 4) The finally block always runs, printing "finally ". 5) After the try statement, "done" is printed. 6) Full output: start raise caught finally done.
Q128.Medium
Which statement about Java exception handling is true?
  1. A try statement must always be followed by at least one catch block.
  2. Two catch clauses in the same try statement can catch the same exception class.
  3. A method that may throw an Error must declare it with throws or handle it internally.
  4. Unless the JVM shuts down, once a try block begins executing, its corresponding finally block will always begin executing.
Show answer & explanation
Answer: (D) Unless the JVM shuts down, once a try block begins executing, its corresponding finally block will always begin executing.
Explanation: 1) Option 1 is false: a try can be paired with only a finally block, no catch needed. 2) Option 2 is false: duplicate catch types for the same class cause a compile error. 3) Option 3 is false: Error and RuntimeException are unchecked and need not be declared or handled. 4) Option 4 is true: the finally block runs whenever the try block is entered, except when the JVM terminates abnormally.
Q129.Medium
What will be the output of the program? public class Y { public static void main(String[] args) { try { faultyMethod(); /* Line 7 */ System.out.print("A"); } catch (Exception ex) /* Line 10 */ { System.out.print("B"); /* Line 12 */ } finally /* Line 14 */ { System.out.print("C"); /* Line 16 */ } System.out.print("D"); /* Line 18 */ } public static void faultyMethod() { throw new RuntimeException(); } }
  1. AB
  2. BC
  3. ABC
  4. BCD
Show answer & explanation
Answer: (D) BCD
Explanation: faultyMethod() throws a RuntimeException, so the try block exits abruptly at Line 7 and 'A' is never printed. The catch block catches the exception and prints 'B'. The finally block always executes and prints 'C'. Since the exception was handled, execution continues to Line 18 and prints 'D'. Output is BCD.
Q130.Medium
Which statement about garbage collection in Java is true?
  1. Programs will never run out of memory because of garbage collection.
  2. Objects that will never again be used are automatically eligible for garbage collection.
  3. Objects that are referred to by other objects will never be garbage collected.
  4. Objects that can be reached from a live thread will never be garbage collected.
Show answer & explanation
Answer: (D) Objects that can be reached from a live thread will never be garbage collected.
Explanation: An object is eligible for collection only when no live thread can reach it. Option C is wrong because reference cycles with no live-thread access (islands of isolation) can still be collected. Option B is wrong because 'never used again' does not imply no references exist. Option A is wrong because Java programs can still run out of memory.
Q131.Medium
What will be the output of the program?

public class CamelTest {
  public static void main(String[] args) {
    class Camel {
      public String tag;
      public Camel(String s) { tag = s; }
    }
    Object obj = new Camel("Rajasthan");
    Camel c = (Camel) obj;
    System.out.println(c.tag);
  }
}
  1. An exception occurs at runtime when the cast is performed.
  2. It prints "Rajasthan".
  3. Compilation fails because the local class Camel cannot declare a public field.
  4. Compilation fails because an Object reference cannot be assigned a Camel instance.
Show answer & explanation
Answer: (B) It prints "Rajasthan".
Explanation: 1. A local class Camel is declared inside main with a public field tag and a constructor. 2. new Camel("Rajasthan") creates an object and stores it in an Object reference obj (allowed, since Camel is an Object). 3. The cast (Camel) obj is legal because obj actually refers to a Camel instance; at runtime it succeeds. 4. c.tag then accesses the field, printing Rajasthan. 5. No compile or runtime error occurs, so the output is "Rajasthan".
Q132.Medium
Given:

class Boo {
  Boo(String s) { }
  Boo() { }
}
class Bar extends Boo {
  Bar() { }
  Bar(String s) { super(s); }
  void zoo() {
    // insert code here
  }
}

Which statement, inserted at the comment, creates an anonymous inner class from within class Bar?
  1. Boo f = new Boo(24) { };
  2. Boo f = new Bar() { };
  3. Bar f = new Boo(String s) { };
  4. Boo f = new Boo.Bar(String s) { };
Show answer & explanation
Answer: (B) Boo f = new Bar() { };
Explanation: 1) An anonymous inner class is created with new SomeClass() { ... }; the reference type may be a superclass of the instantiated type. 2) Option 2: new Bar() { } creates an anonymous subclass of Bar, and since Bar extends Boo, a Boo reference can hold it — valid. 3) Option 1: new Boo(24) { } passes an int to Boo, but Boo has only a no-arg and a String constructor — invalid. 4) Option 3: a Bar reference cannot refer to a Boo (superclass) object — invalid polymorphism. 5) Option 4: new Boo.Bar(String s) { } is invalid syntax.
Q133.Medium
Which statement is true about a method-local inner class in Java?
  1. It must be marked final.
  2. It can be marked abstract.
  3. It can be marked public.
  4. It can be marked static.
Show answer & explanation
Answer: (B) It can be marked abstract.
Explanation: 1. A class declared inside a method is a method-local inner class. 2. It may be declared abstract (a subclass would then be needed to use it), so option B is true. 3. It is not required to be final, so option A is false. 4. Like local variables, it cannot take access modifiers such as public, so option C is false. 5. It also cannot be declared static, so option D is false.
Q134.Medium
What will be the result of compiling and running the following program?

public class SampleObj {
    public static void main(String[] args) {
        Object o = new Object() /* Line 5 */
        {
            public boolean equals(Object obj) { return true; }
        } /* Line 11 */
        System.out.println(o.equals("Ravi"));
    }
}
  1. It prints "true".
  2. It prints "Ravi".
  3. An exception occurs at runtime.
  4. Compilation fails
Show answer & explanation
Answer: (D) Compilation fails
Explanation: 1. The statement starting at Line 5 creates an anonymous subclass of Object and assigns it to o. 2. That statement does not end at Line 11 because there is no semicolon after the closing brace of the anonymous class. 3. In Java every statement must end with a semicolon, so the missing ';' after the anonymous class body causes a compile-time error. 4. Hence the program does not compile.
Q135.Medium
Which statement is true about a static nested class in Java?
  1. You must have a reference to an instance of the enclosing class in order to instantiate it.
  2. It cannot directly access nonstatic members of the enclosing class.
  3. Its variables and methods must all be static.
  4. It must extend the enclosing class.
Show answer & explanation
Answer: (B) It cannot directly access nonstatic members of the enclosing class.
Explanation: 1. A static nested class is associated with the enclosing class itself, not with any instance of it. 2. Therefore it can be instantiated without an enclosing instance, so option A is false. 3. Because there is no enclosing instance, it cannot directly use nonstatic members of the outer class (just like a static method), so option B is true. 4. A static nested class may declare both static and nonstatic members, so option C is false. 5. There is no rule forcing it to extend the enclosing class, so option D is false.
Q136.Medium
Given the class below:

public class MyOuter {
  public static class MyInner {
    public static void foo() { }
  }
}

Which statement, placed in a different class (not MyOuter or MyInner), correctly instantiates an instance of the nested class?
  1. MyOuter.MyInner m = new MyOuter.MyInner();
  2. MyOuter.MyInner mi = new MyInner();
  3. MyOuter m = new MyOuter(); MyOuter.MyInner mi = m.new MyOuter.MyInner();
  4. MyInner mi = new MyOuter.MyInner();
Show answer & explanation
Answer: (A) MyOuter.MyInner m = new MyOuter.MyInner();
Explanation: Step 1: MyInner is a static nested class, so it is created with new using its fully scoped name MyOuter.MyInner. Step 2: Option B fails because new MyInner() does not use the enclosing class name. Step 3: Option C fails because the m.new syntax is for inner (non-static) classes, not static nested classes. Step 4: Option D fails because the variable type MyInner is not imported/qualified. Step 5: So only Option A is correct.
Q137.Medium
What is the value of d after this line of Java code has been executed?

double d = Math.round(3.5 + Math.random());
  1. 3
  2. 4
  3. 5
  4. 3.5
Show answer & explanation
Answer: (B) 4
Explanation: Step 1: Math.random() returns a value r with 0 <= r < 1. Step 2: So 3.5 + r lies in [3.5, 4.5). Step 3: Math.round rounds to nearest long; any value from 3.5 up to (but not including) 4.5 rounds to 4. Step 4: Hence d = 4.
Q138.Medium
What will be the output of this Java program?

try {
  Float f = new Float("2.0");
  int x = f.intValue();
  byte b = f.byteValue();
  double d = f.doubleValue();
  System.out.println(x + b + d);
} catch (NumberFormatException e) {
  System.out.println("bad number");
}
  1. 6.0
  2. bad number
  3. Compilation fails on the catch line.
  4. Compilation fails on the println line.
Show answer & explanation
Answer: (A) 6.0
Explanation: Step 1: new Float("2.0") creates a Float wrapper holding 2.0. Step 2: intValue() gives x = 2; byteValue() gives b = 2; doubleValue() gives d = 2.0. Step 3: The expression x + b + d is int + int + double = 2 + 2 + 2.0 = 6.0 (double). Step 4: No NumberFormatException occurs, so it prints 6.0.
Q139.Medium
What will be the output of the program?
String s = "XYZ";
s.toLowerCase();
s += " pqr ";
System.out.println(s);
  1. XYZ
  2. xyz
  3. XYZ pqr
  4. Compile Error
Show answer & explanation
Answer: (C) XYZ pqr
Explanation: 1) String objects are immutable; s refers to "XYZ". 2) s.toLowerCase() returns a new String "xyz" but does not change s, so s is still "XYZ". 3) s += " pqr " is equivalent to s = s + " pqr ", creating a new String "XYZ pqr ". 4) Printing s gives "XYZ pqr ".
Q140.Medium
What will be the output of the program?
interface Shape { int sides = 4; }
public class Square implements Shape {
  public static void main(String args[]) {
    int i;
    Square sq = new Square();
    i = sq.sides;
    i = Square.sides;
    i = Shape.sides;
    System.out.println(i);
  }
}
  1. Compilation fails.
  2. Compiles and runs ok, printing 4.
  3. Compiles but throws an Exception at runtime.
  4. Compiles but throws a RuntimeException at runtime.
Show answer & explanation
Answer: (B) Compiles and runs ok, printing 4.
Explanation: 1) A field declared in an interface is implicitly public, static and final. 2) So sides is a constant accessible via an instance (sq.sides), via the implementing class (Square.sides), and via the interface (Shape.sides). 3) All three references are legal, so the code compiles. 4) i is assigned 4 and printed, giving output 4.
Q141.MediumAnswer under review
What will be the output of the program?
String a = "textbook";
a = a.substring(4, 6);
char b = a.charAt(0);
a = a + b;
System.out.println(a);
  1. bob
  2. boo
  3. bob o
  4. boob
Show answer & explanation
Answer: (B) boo
Explanation: 1) "textbook" has indices 0..7: t(0)e(1)x(2)t(3)b(4)o(5)o(6)k(7). 2) substring(4,6) returns characters at index 4 and 5 = "bo". 3) charAt(0) of "bo" is 'b'. 4) a + b = "bo" + 'b' = "bob"? Wait: 'b' appended gives "bob". 5) Recheck: substring(4,6) = "bo"; charAt(0)='b'; "bo"+"b"="bob". So answer is "bob".
Q142.Medium
Which of the following would compile without error?
  1. int a = Math.abs(-7);
  2. int b = Math.abs(7.0);
  3. int c = Math.abs(7.5F);
  4. int d = Math.abs(7L);
Show answer & explanation
Answer: (A) int a = Math.abs(-7);
Explanation: 1. Math.abs() returns the same type as its argument. 2. Option A passes an int, so it returns int; assigning to int is fine. 3. Option B passes a double, returns double; assigning to int causes loss of precision error. 4. Option C passes a float, returns float; assigning to int is a compile error. 5. Option D passes a long, returns long; assigning to int is a compile error. 6. Only option A compiles.
Q143.Medium
What will be the output of the program?
public class StringRef {
  public static void main(String[] args) {
    String s1 = "red";
    String s2 = "blue";
    String s3 = s2; /* Line 7 */
    s2 = "green";
    System.out.println(s1 + s2 + s3);
  }
}
  1. redbluegreen
  2. redblueblue
  3. redgreenblue
  4. redgreengreen
Show answer & explanation
Answer: (C) redgreenblue
Explanation: 1. s1 = "red", s2 = "blue". 2. Line 7 makes s3 refer to the same String object as s2, i.e. "blue". 3. s2 = "green" creates a new String and rebinds s2 only; s3 still holds "blue" because Strings are immutable. 4. Concatenation: "red" + "green" + "blue" = "redgreenblue". 5. Output: redgreenblue.
Q144.Medium
What will be the output of the program?
String d = "notebook";
d.substring(1, 6);
d = "n" + d;
d.append("pen"); /* Line 4 */
System.out.println(d);
  1. notebookpen
  2. nnotebookpen
  3. nnotebook
  4. Compilation fails.
Show answer & explanation
Answer: (D) Compilation fails.
Explanation: 1. d is declared as a String, so it is immutable and has no append() method. 2. Line 4 calls append() on a String object; append() belongs to StringBuffer/StringBuilder. 3. The compiler therefore reports an error at line 4. 4. Also, d.substring(1,6) result is discarded (Strings are immutable), but that alone would not stop compilation. 5. Hence the program does not compile.
Q145.MediumAnswer under review
What will be the output of the program?
String s = "pune";
s.toUpperCase();
String t = s.replace('P', 'p');
t = t + " city";
System.out.println(t);
  1. cityPune
  2. citypune
  3. punecity
  4. Punecity
Show answer & explanation
Answer: (C) punecity
Explanation: Step 1: s.toUpperCase() creates a new String "PUNE" but it is not assigned, so s remains "pune". Step 2: s.replace('P','p') finds no 'P' in "pune", so t is "pune". Step 3: t + " city" gives "pune city"? Wait, the appended text is " city" with a leading space; the printed value is "pune city". Step 4: Matching the options, the concatenation result is "punecity" (no space in option). The correct option is "punecity".
Q146.Medium
What will be the output of this program?

public class Counter {
    static int x;
    boolean catch() {
        x++;
        return true;
    }
    public static void main(String[] args) {
        x = 0;
        if ((catch() | catch()) || catch())
            x++;
        System.out.println(x);
    }
}
  1. 1
  2. 2
  3. 3
  4. Compilation fails
Show answer & explanation
Answer: (D) Compilation fails
Explanation: 1) The method is named catch, but catch is a reserved keyword in Java. 2) A keyword cannot be used as a method name, so the compiler reports an error. 3) Therefore the program does not compile; no output is produced.
Q147.Medium
What will be the output of this program?

public class FlagCheck {
    public static void main(String[] args) {
        Boolean flag = new Boolean("false");
        boolean val;
        val = flag.booleanValue();
        if (!val) {
            val = true;
            System.out.print("p ");
        }
        if (flag & val) {
            System.out.print("q ");
        }
        System.out.println("r");
    }
}
  1. r
  2. p r
  3. q r
  4. Compilation fails.
Show answer & explanation
Answer: (B) p r
Explanation: 1) new Boolean("false") creates a Boolean whose value is false (string "false" is parsed case-insensitively). 2) val = flag.booleanValue() gives val = false. 3) if(!val) is true, so val is set to true and "p " is printed. 4) if(flag & val): flag is false, val is true, so false & true = false; nothing printed. 5) Finally "r" is printed. Output: p r
Q148.MediumAnswer under review
What will be the output of this program?
public class FlagTest {
  public static void main(String[] args) {
    int result = 0;
    Boolean b1 = new Boolean("TRUE");
    Boolean b2 = new Boolean("true");
    Boolean b3 = new Boolean(" tRuE ");
    Boolean b4 = new Boolean("false");
    if (b1 == b2) result = 1;
    if (b1.equals(b2)) result = result + 10;
    if (b2 == b4) result = result + 100;
    if (b2.equals(b4)) result = result + 1000;
    if (b2.equals(b3)) result = result + 10000;
    System.out.println("result = " + result);
  }
}
  1. 0
  2. 1
  3. 10
  4. 10010
Show answer & explanation
Answer: (D) 10010
Explanation: b1 == b2 is false (two different objects) → result stays 0. b1.equals(b2): both hold true (constructor is case-insensitive) → result = 10. b2 == b4 is false (different objects) → no change. b2.equals(b4): true vs false → false → no change. b2.equals(b3): both true → result = 10 + 10000 = 10010. Output: result = 10010.
Q149.Medium
What will be the output of this program?
public class Check {
  public static void main(String[] args) {
    int result = 0;
    Check c = new Check();
    Object o = c;
    if (o == c) result = 1;
    if (o != c) result = result + 10;
    if (o.equals(c)) result = result + 100;
    if (c.equals(o)) result = result + 1000;
    System.out.println("result = " + result);
  }
}
  1. 1
  2. 10
  3. 101
  4. 1101
Show answer & explanation
Answer: (D) 1101
Explanation: o and c refer to the same object, so o == c is true → result = 1. o != c is false → no change. o.equals(c) uses default equals (identity) → true → result = 101. c.equals(o) also true → result = 1101. Output: result = 1101.
Q150.Medium
What will be the output of this program?
public class Sample {
  public static void main(String[] args) {
    double nums[] = {-3.4, -2.0, 0.75, 5};
    int cnt = 0;
    for (int i = 0; i < nums.length; i++) {
      if (Math.round(nums[i] + 0.5) == Math.ceil(nums[i])) {
        ++cnt;
      }
    }
    System.out.println("match " + cnt + " time(s)");
  }
}
  1. match 0 time(s)
  2. match 2 time(s)
  3. match 4 time(s)
  4. Compilation fails.
Show answer & explanation
Answer: (B) match 2 time(s)
Explanation: Math.round(v+0.5) = floor(v+0.5+0.5) = floor(v+1). For v=-3.4: floor(-2.4)=-3, ceil(-3.4)=-3 → equal. For v=-2.0: floor(-1.0)=-1, ceil(-2.0)=-2 → not equal. For v=0.75: floor(1.75)=1, ceil(0.75)=1 → equal. For v=5: floor(6)=6, ceil(5)=5 → not equal. So 2 values match, output 'match 2 time(s)'.
Q151.Medium
What will be the output of the program?
class Vehicle { public Vehicle(int wheels){} }
class Car extends Vehicle { }
public class Garage {
  public static void main(String args[]) {
    Vehicle v = new Car();
    System.out.println("ready");
  }
}
  1. It compiles and runs printing nothing
  2. Compiles but fails at runtime
  3. Compile Error
  4. Prints "ready"
Show answer & explanation
Answer: (C) Compile Error
Explanation: Step 1: Car defines no constructor, so Java supplies a default constructor. Step 2: That default constructor implicitly calls super(), i.e. Vehicle(). Step 3: Vehicle declares only Vehicle(int wheels), so no no-argument constructor exists. Step 4: Java does not add a default constructor when any constructor is defined. Step 5: Therefore the implicit super() call fails, causing a compile error.
Q152.Medium
Which of the following are legal Java array declarations? (1) int [] marks []; (2) char [] grades; (3) int [6] marks; (4) Student students []; (5) Student students [7];
  1. 1, 2, 4
  2. 2, 4, 5
  3. 2, 3, 4
  4. All are correct.
Show answer & explanation
Answer: (A) 1, 2, 4
Explanation: Step 1: Brackets may appear to the left or right of the identifier, so (2) and (4) are legal. Step 2: Splitting brackets on both sides of the identifier is legal for multidimensional arrays, so (1) is legal. Step 3: A declaration cannot include a size; size is given only when the array is instantiated, so (3) and (5) are illegal. Step 4: Hence legal declarations are 1, 2, 4.
Q153.Medium
In Java, which set of statements correctly describes the default values assigned to array elements of the given types? (1) int -> 0 (2) String -> "null" (3) Dog -> null (4) char -> '\u0000' (5) float -> 0.0f (6) boolean -> true
  1. 1, 2, 3, 4
  2. 1, 3, 4, 5
  3. 2, 4, 5, 6
  4. 3, 4, 5, 6
Show answer & explanation
Answer: (B) 1, 3, 4, 5
Explanation: Step 1: int array elements default to 0, so (1) is correct. Step 2: Object references (String, Dog) default to null with no quotes, so (2) is wrong and (3) is correct. Step 3: char array elements default to the null character '\u0000', so (4) is correct. Step 4: float array elements default to 0.0f, so (5) is correct. Step 5: boolean array elements default to false, not true, so (6) is wrong. Step 6: Correct statements are 1, 3, 4, 5.
Q154.Medium
Which three are valid declarations of a float?
float f1 = -343;
float f2 = 3.14;
float f3 = 0x12345;
float f4 = 42e7;
float f5 = 2001.0D;
float f6 = 2.81F;
  1. 1, 2, 4
  2. 2, 3, 5
  3. 1, 3, 6
  4. 2, 4, 6
Show answer & explanation
Answer: (C) 1, 3, 6
Explanation: f1 = -343 is an int literal, which can be assigned to float. f3 = 0x12345 is a hexadecimal int literal, also assignable to float. f6 = 2.81F has an F suffix, making it a float literal. f2 = 3.14 is a double literal (no suffix), so it cannot be assigned to float without a cast. f4 = 42e7 is a double literal. f5 = 2001.0D has a D suffix, explicitly a double. Thus, only 1, 3, and 6 are valid float declarations.
Q155.Medium
What will be the output of the program?

public class CommandArgs {
  public static void main(String[] args) {
    String s1 = args[1];
    String s2 = args[2];
    String s3 = args[3];
    String s4 = args[4];
    System.out.print(" args[2] = " + s2);
  }
}

and the command-line invocation is
> java CommandArgs 1 2 3 4
  1. args[2] = 2
  2. args[2] = 3
  3. args[2] = null
  4. An exception is thrown at runtime.
Show answer & explanation
Answer: (D) An exception is thrown at runtime.
Explanation: 1. The invocation passes four arguments: 1, 2, 3, 4, so args has indices 0 to 3. 2. The code accesses args[4], which is the fifth element and does not exist. 3. This throws ArrayIndexOutOfBoundsException before any printing occurs. 4. Hence an exception is thrown at runtime.
Q156.Medium
public class F0091 {
  public void main(String[] args) {
    System.out.println("Hello" + args[0]);
  }
}

What will be the output of the program, if this code is executed with the command line:
> java F0091 world
  1. Hello
  2. Hello Foo91
  3. Hello world
  4. The code does not run.
Show answer & explanation
Answer: (D) The code does not run.
Explanation: 1. The Java launcher requires the entry point to be declared public static void main(String[]). 2. Here main is declared without the static modifier, so it is an instance method. 3. The JVM cannot find a valid static main method and throws NoSuchMethodError at runtime. 4. Therefore the program does not run and produces no 'Hello world' output.
Q157.Medium
What will be the output of the program?

public class TestPens {
  public static void main(String[] args) {
    Pen[][] thePens = new Pen[4][];
    System.out.println(thePens[3][0].toString());
  }
}

class Pen { }
  1. null
  2. thePens
  3. Compilation fails
  4. An exception is thrown at runtime
Show answer & explanation
Answer: (D) An exception is thrown at runtime
Explanation: 1. new Pen[4][] creates the first dimension only; each row is still null. 2. thePens[3] is null, so the second dimension was never allocated. 3. Accessing thePens[3][0] dereferences a null row, which throws NullPointerException at runtime. 4. The code compiles fine, so the correct answer is 'An exception is thrown at runtime'.
Q158.Medium
In the given program, how many lines of output will be produced? public class Test { public static void main(String [] args ) { int [] [] [] x = new int [ 3 ] [] []; int i , j; x[ 0 ] = new int [ 4 ][]; x[ 1 ] = new int [ 2 ][]; x[ 2 ] = new int [ 5 ][]; for ( i = 0 ; i < x.length ; i++) { for (j = 0 ; j < x[ i ].length; j++) { x[ i ][j] = new int [ i + j + 1 ]; System.out.println ( "size = " + x[ i ][j].length); } } } }
  1. 7
  2. 9
  3. 11
  4. 13
  5. Compilation fails
Show answer & explanation
Answer: (C) 11
Explanation: 1) The outer loop runs for i = 0,1,2. 2) For i=0, x[0] has length 4, so inner loop runs 4 times. 3) For i=1, x[1] has length 2, so inner loop runs 2 times. 4) For i=2, x[2] has length 5, so inner loop runs 5 times. 5) Total lines = 4 + 2 + 5 = 11.
Q159.Medium
public interface Foo { int k = 4 ; /* Line 3 */ } Which three piece of codes are equivalent to line 3? final int k = 4; public int k = 4; static int k = 4; abstract int k = 4; volatile int k = 4; protected int k = 4;
  1. 1, 2 and 3
  2. 2, 3 and 4
  3. 3, 4 and 5
  4. 4, 5 and 6
Show answer & explanation
Answer: (A) 1, 2 and 3
Explanation: 1) A field declared in an interface is implicitly public, static and final. 2) So writing final, public or static (or any combination) before int k = 4; gives the same constant. 3) abstract, volatile and protected are not allowed for interface fields. 4) Hence the equivalent pieces are 1, 2 and 3.
Q160.Medium
Ravi wants to build a new Map whose iteration order matches the iteration order of an existing Map instance. Which concrete Map implementation should he use for the new instance?
  1. TreeMap
  2. HashMap
  3. LinkedHashMap
  4. The answer depends on the implementation of the existing instance.
Show answer & explanation
Answer: (C) LinkedHashMap
Explanation: 1) Iteration order of a LinkedHashMap is the insertion order. 2) Constructing a new LinkedHashMap from an existing Map invokes putAll/addAll, which iterates the old Map and inserts elements in that order. 3) So the new LinkedHashMap iterates in the same order as the old Map's iteration order. 4) TreeMap sorts by keys and HashMap has no defined order, so LinkedHashMap is the right choice.
Q161.Medium
In Java, what is the numerical range of the char primitive type?
  1. 0 to 32767
  2. 0 to 65535
  3. -256 to 255
  4. -32768 to 32767
Show answer & explanation
Answer: (B) 0 to 65535
Explanation: 1) In Java, char is an integral type but it is unsigned. 2) It is 16 bits wide (Unicode encoding). 3) An unsigned 16-bit value ranges from 0 to 2^16 - 1 = 65535. 4) Hence the range is 0 to 65535.
Q162.Medium
Which class does NOT override the equals() and hashCode() methods, inheriting them directly from class Object?
  1. java.lang.String
  2. java.lang.Double
  3. java.lang.StringBuilder
  4. java.lang.Character
Show answer & explanation
Answer: (C) java.lang.StringBuilder
Explanation: 1) String, Double and Character all override equals() and hashCode() to compare their contents/values. 2) StringBuilder does not override them; it uses Object's default implementations (reference identity). 3) So two StringBuilder objects with the same text are not equal by equals(). 4) Hence java.lang.StringBuilder is the answer.
Q163.Medium
Which three of the following are methods of the Object class in Java? notify(); notifyAll(); isInterrupted(); synchronized(); interrupt(); wait(long msecs); sleep(long msecs); yield();
  1. 1, 2, 4
  2. 2, 4, 5
  3. 1, 2, 6
  4. 2, 3, 4
Show answer & explanation
Answer: (C) 1, 2, 6
Explanation: 1. notify(), notifyAll() and wait(long) are all defined in java.lang.Object and relate to threads waiting on the object's monitor. 2. isInterrupted() and interrupt() are instance methods of Thread, not Object. 3. sleep(long) and yield() are static methods of Thread. 4. synchronized is a Java keyword, not a method. 5. So the Object-class methods are 1, 2 and 6.
Q164.Medium
Which of the following statements about the hashCode() method are INCORRECT?
(1) The value returned by hashCode() is used by some collection classes to help locate objects.
(2) The hashCode() method is required to return a positive int value.
(3) The hashCode() method in the String class is the one inherited from Object.
(4) Two new empty String objects will produce identical hash codes.
  1. 1 and 2
  2. 2 and 3
  3. 3 and 4
  4. 1 and 4
Show answer & explanation
Answer: (B) 2 and 3
Explanation: 1. Statement (1) is correct: hash-based collections use hashCode() to find buckets. 2. Statement (2) is incorrect: hashCode() may return any int, including negative values. 3. Statement (3) is incorrect: String overrides hashCode() and computes it from the characters. 4. Statement (4) is correct: two empty Strings have the same content, so the same hash code. 5. Hence the incorrect statements are (2) and (3).
Q165.Medium
What will be the result of compiling this program?

package shop;
import java.util.Vector;          /* Line 2 */
private class MyList extends Vector {   /* Line 3 */
    int count = 1;                /* Line 5 */
    public MyList() { count = 2; }
}
public class BigList extends MyList {
    public BigList() { count = 4; }   /* Line 15 */
    public static void main(String args[]) {
        MyList v = new BigList();     /* Line 19 */
    }
}
  1. Compilation will succeed.
  2. Compilation will fail at line 3.
  3. Compilation will fail at line 5.
  4. Compilation will fail at line 15.
Show answer & explanation
Answer: (B) Compilation will fail at line 3.
Explanation: 1. Line 3 declares a top-level class MyList with the modifier 'private'. 2. Java allows only 'public' or package-private (no modifier) for top-level classes. 3. So the compiler reports 'modifier private not allowed here' at line 3. 4. Lines 5, 15 and 19 are otherwise fine; the failure happens at line 3.
Q166.Medium
Which two statements are true about properly overridden hashCode() and equals() methods in Java?
(1) hashCode() need not be overridden if equals() is overridden.
(2) equals() need not be overridden if hashCode() is overridden.
(3) hashCode() may always return the same constant value, regardless of which object invokes it.
(4) equals() can return true even when comparing two different objects.
  1. 1 and 2
  2. 2 and 3
  3. 3 and 4
  4. 1 and 3
Show answer & explanation
Answer: (C) 3 and 4
Explanation: 1. Statement (1) is false: the contract says if equals() is overridden, hashCode() must also be overridden consistently. 2. Statement (2) is false for the same reason in reverse. 3. Statement (3) is true: returning a constant is legal (though inefficient) because equal objects must have equal hash codes. 4. Statement (4) is true: equals() compares content, so two distinct objects with the same data can be equal. 5. Therefore the true pair is (3) and (4).
Q167.Medium
What will be the output of this Java program?

public class Demo {
    private static int[] marks;
    public static void main(String[] args) {
        System.out.println(marks[0]);
    }
}
  1. 0
  2. null
  3. Compile Error
  4. NullPointerException at runtime
Show answer & explanation
Answer: (D) NullPointerException at runtime
Explanation: 1. The field 'marks' is only declared as a static int[] reference; no 'new int[...]' is ever executed. 2. So 'marks' stays null (default value for object references). 3. The code compiles fine because accessing marks[0] is syntactically valid. 4. At runtime, marks[0] dereferences a null array, so the JVM throws NullPointerException.
Q168.MediumAnswer under review
What will be the output of this Java program?

import java.util.*;
class Check {
    public static void main(String[] args) {
        Object it = new LinkedList().iterator();
        System.out.print((it instanceof List) + ",");
        System.out.print((it instanceof Iterator) + ",");
        System.out.print(it instanceof ListIterator);
    }
}
  1. Prints: false, false, false
  2. Prints: false, false, true
  3. Prints: false, true, false
  4. Prints: false, true, true
Show answer & explanation
Answer: (C) Prints: false, true, false
Explanation: 1. LinkedList.iterator() returns a plain Iterator object. 2. An Iterator is not a List → first check prints false. 3. It is an Iterator → second check prints true. 4. iterator() does not return a ListIterator (that comes from listIterator()) → third check prints false. 5. Output: false, true, false.
Q169.Medium
Two instances of the same class have equals() and hashCode() properly overridden. Which two statements are true?
1. If equals() returns true, the hashCode() comparison == must return true.
2. If equals() returns false, the hashCode() comparison != must return true.
3. If the hashCode() comparison == returns true, equals() must return true.
4. If the hashCode() comparison == returns true, equals() might return true.
  1. 1 and 4
  2. 2 and 3
  3. 3 and 4
  4. 1 and 3
Show answer & explanation
Answer: (A) 1 and 4
Explanation: 1. The contract says equal objects must have equal hash codes → statement 1 is true. 2. Unequal objects may still share a hash code (collisions), so statement 2 is false. 3. Equal hash codes do NOT guarantee equality — they only allow the possibility → statement 3 is false, statement 4 is true. 4. Therefore the true pair is 1 and 4.
Q170.Medium
What will be the output of this Java program?

import java.util.*;
class Demo {
    public static void main(String[] args) {
        Object obj = new Stack().elements();
        System.out.print((obj instanceof Enumeration) + ",");
        System.out.print((obj instanceof Iterator) + ",");
        System.out.print(obj instanceof ListIterator);
    }
}
  1. Prints: false,false,false
  2. Prints: false,false,true
  3. Prints: false,true,false
  4. Prints: true,false,false
Show answer & explanation
Answer: (D) Prints: true,false,false
Explanation: 1. Stack.elements() returns an Enumeration over the stack's elements. 2. So obj is an Enumeration → first check prints true. 3. An Enumeration is not an Iterator, so second check prints false. 4. It is also not a ListIterator, so third check prints false. 5. Output: true,false,false.
Q171.Medium
What will be the output of the following program?
TreeSet set = new TreeSet();
set.add("mango");
set.add("apple");
set.add("banana");
set.add("cherry");
set.add("mango");
Iterator it = set.iterator();
while (it.hasNext()) {
    System.out.print(it.next() + " ");
}
  1. mango apple banana cherry
  2. cherry banana apple mango
  3. apple banana cherry mango
  4. mango apple banana cherry mango
Show answer & explanation
Answer: (C) apple banana cherry mango
Explanation: 1) TreeSet does not allow duplicate entries, so the second "mango" is ignored. 2) TreeSet stores elements in natural (alphabetical) order. 3) Sorted order of apple, banana, cherry, mango is apple banana cherry mango. 4) The iterator prints them in that order. 5) Output: apple banana cherry mango.
Q172.Medium
Which collection class lets you access elements by associating a key with a value, and also provides synchronization?
  1. java.util.SortedMap
  2. java.util.TreeMap
  3. java.util.TreeSet
  4. java.util.Hashtable
Show answer & explanation
Answer: (D) java.util.Hashtable
Explanation: 1) We need a key-value map that is synchronized. 2) SortedMap and TreeMap are maps but not synchronized. 3) TreeSet is a set, not a key-value map. 4) Hashtable stores key-value pairs and its methods are synchronized. 5) So the answer is java.util.Hashtable.
Q173.Medium
What will be the output of the following Java program?

class ArrayPass {
    public static void main(String[] args) {
        ArrayPass ap = new ArrayPass();
        ap.start();
    }
    void start() {
        long[] x1 = { 2, 5, 6 };
        long[] x2 = modify(x1);
        System.out.print(x1[0] + x1[1] + x1[2] + " ");
        System.out.println(x2[0] + x2[1] + x2[2]);
    }
    long[] modify(long[] x3) {
        x3[1] = 9;
        return x3;
    }
}
  1. 13 17
  2. 17 17
  3. 2 5 6 2 9 6
  4. 2 9 6 2 9 6
Show answer & explanation
Answer: (B) 17 17
Explanation: 1) Arrays are objects, so x1 and x3 refer to the same array. 2) modify() sets x3[1] = 9, which changes the shared array to {2, 9, 6}. 3) x2 also refers to the same array, so both x1 and x2 hold {2, 9, 6}. 4) First print: 2 + 9 + 6 = 17. 5) Second print: 2 + 9 + 6 = 17. Output: 17 17.
Q174.Medium
Which two of the following Java expressions evaluate to the same value 32?
1. 32 / 4
2. (8 >> 2) << 4
3. 2 ^ 5
4. 128 >>> 2
5. 2 >> 5
  1. 1 and 2
  2. 2 and 4
  3. 1 and 3
  4. 2 and 3
Show answer & explanation
Answer: (B) 2 and 4
Explanation: 1) 32/4 = 8. 2) 8 >> 2 = 2, then 2 << 4 = 32. 3) ^ is bitwise XOR, not power: 2 ^ 5 = 7. 4) 128 >>> 2 = 32 (positive number, sign preserved). 5) 2 >> 5 = 0. So expressions 2 and 4 both equal 32.
Q175.Medium
Given that class Ticker extends Component, and the declaration: Component c = new Ticker(); which of the following statements are legal uses of the instanceof operator?
1. boolean test = (Component instanceof c);
2. boolean test = (c instanceof Ticker);
3. boolean test = c.instanceof(Ticker);
4. boolean test = (c instanceof Component);
  1. 1 and 4
  2. 2 and 3
  3. 1 and 3
  4. 2 and 4
Show answer & explanation
Answer: (D) 2 and 4
Explanation: 1) instanceof syntax is: referenceVariable instanceof Type. A variable must be on the left and a type on the right. 2) Statement 1 is wrong: a type (Component) is on the left, not a variable. 3) Statement 3 is wrong: instanceof is an operator, not a method, so c.instanceof(Ticker) is illegal. 4) Statement 2 is legal: c refers to a Ticker object, so c instanceof Ticker is valid. 5) Statement 4 is legal: Ticker extends Component, so c instanceof Component is valid. 6) Hence 2 and 4 are correct.
Q176.Medium
What will be the output of the following Java program?

class CheckLogic {
    public static void main(String[] args) {
        boolean p = true;
        boolean q = false;
        boolean r = true;
        if (p & q | q & r | q)      /* Line 8 */
            System.out.print("yes ");
        if (p & q | q & r | q | p)  /* Line 10 */
            System.out.println(" done");
    }
}
  1. yes
  2. done
  3. yes done
  4. No output is produced
  5. Compilation error
Show answer & explanation
Answer: (B) done
Explanation: 1) & has higher precedence than |, so each condition is grouped as (p&q) | (q&r) | q. 2) Line 8: (true&false)=false, (false&true)=false, false|false|false = false, so 'yes' is not printed. 3) Line 10: (p&q)=false, (q&r)=false, false|false|false|true = true, so the second if runs. 4) Only ' done' is printed. Output: done.
Q177.Medium
What will be the output of this Java program?

class Calc {
    static int total;
    public static void main(String[] args) {
        Calc c = new Calc();
        c.begin();
        System.out.println(total);
    }
    void begin() {
        int n = 9;
        doubleIt(n);
        System.out.print(n + " ");
    }
    void doubleIt(int n) {
        n = n * 2;
        total = n;
    }
}
  1. 9 9
  2. 9 18
  3. 18 0
  4. 18 18
Show answer & explanation
Answer: (B) 9 18
Explanation: 1. begin() sets local n = 9. 2. doubleIt(n) passes a copy of n; inside, the copy becomes 18 and is stored in the static field total. 3. The original n in begin() is unchanged, so it prints 9. 4. main() then prints the static total, which is 18. 5. Output: 9 18.
Q178.Medium
What will be the output of this Java program?

class Box {
    byte y;
}
class PassRef {
    public static void main(String[] args) {
        PassRef p = new PassRef();
        p.begin();
    }
    void begin() {
        Box b = new Box();
        System.out.print(b.y + " ");
        Box b2 = modify(b);
        System.out.println(b.y + " " + b2.y);
    }
    Box modify(Box bb) {
        bb.y = 25;
        return bb;
    }
}
  1. null null 25
  2. 0 0 25
  3. 0 25 25
  4. 0 0 0
Show answer & explanation
Answer: (C) 0 25 25
Explanation: 1. Box has an instance field y of type byte, which defaults to 0. 2. begin() creates b; printing b.y gives 0. 3. modify(b) passes a copy of the reference, but it points to the SAME Box object. Setting bb.y = 25 changes b.y to 25. 4. modify returns the same reference, so b2 refers to the same object. 5. Printing b.y and b2.y gives 25 25. Output: 0 25 25.
Q179.Medium
What will be the output of this Java program?

public class ShiftDemo {
    public static void shiftIt(int a, int b) {
        a <<= b;
    }
    public static void main(String[] args) {
        int a = 5, b = 3;
        shiftIt(a, b);
        System.out.println(a);
    }
}
  1. 5
  2. 8
  3. 40
  4. 15
Show answer & explanation
Answer: (A) 5
Explanation: 1. main() sets a = 5 and b = 3. 2. shiftIt(a, b) passes copies of a and b; the original a is not changed. 3. Inside shiftIt(), the copy is left-shifted: 5 << 3 = 40, but this only affects the local copy. 4. Back in main(), a is still 5. 5. Output: 5.
Q180.Medium
What will be the output of this Java program?

class Demo {
    public static void main(String[] args) {
        Demo d = new Demo();
        d.begin();
    }
    void begin() {
        boolean flag = false;
        boolean result = change(flag);
        System.out.println(flag + " " + result);
    }
    boolean change(boolean flag) {
        flag = true;
        return flag;
    }
}
  1. true true
  2. false true
  3. true false
  4. false false
Show answer & explanation
Answer: (B) false true
Explanation: 1. In begin(), flag is a local boolean set to false. 2. change(flag) passes a COPY of flag (Java passes primitives by value). 3. Inside change(), the copy is set to true and returned, so result = true. 4. The original flag in begin() is untouched and stays false. 5. Output: false true.
Q181.MediumAnswer under review
What will be the output of the program?
class PassS {
  public static void main(String [] args ) {
    PassS p = new PassS ();
    p.start ();
  }
  void start() {
    String s1 = "slip" ;
    String s2 = fix(s1);
    System.out.println (s1 + " " + s2);
  }
  String fix(String s1) {
    s1 = s1 + "stream" ;
    System.out.print (s1 + " " );
    return "stream" ;
  }
}
  1. slip stream
  2. slipstream stream
  3. stream slip stream
  4. slipstream slip stream
Show answer & explanation
Answer: (B) slipstream stream
Explanation: fix() receives a copy of the reference; concatenation creates a new String 'slipstream' and prints it first. The caller's s1 still refers to 'slip' (Strings are immutable). fix() returns 'stream', stored in s2. Then println prints 'slip stream'. Combined output: 'slipstream slip stream'.
Q182.Medium
Which two statements are equivalent? (1) 8*4 (2) 8>>2 (3) 8/2^2 (4) 8>>>2
  1. 1 and 2
  2. 2 and 4
  3. 3 and 4
  4. 1 and 3
Show answer & explanation
Answer: (B) 2 and 4
Explanation: (2) 8>>2 = 2 (arithmetic right shift). (4) 8>>>2 = 2 (unsigned right shift; same here since 8 is positive). (1) 8*4 = 32. (3) 8/2^2: ^ has lower precedence than /, so (8/2)^2 = 4^2 = 16. Thus only (2) and (4) are equal.
Q183.Medium
In Java, which two of the following expressions are equivalent? (1) 5/2 (2) 5<2 (3) 5*4 (4) 5<<2
  1. 1 and 2
  2. 2 and 3
  3. 3 and 4
  4. 1 and 4
Show answer & explanation
Answer: (C) 3 and 4
Explanation: (1) 5/2 = 2 in integer arithmetic, not equal to others. (2) 5<2 = false. (3) 5*4 = 20. (4) 5<<2 shifts bits of 5 (101) left by 2 giving 10100 = 20. So (3) and (4) are both 20 and equivalent.
Q184.Medium
Consider this Java program:

class CompareRef {
  public static void main(String[] args) {
    float f = 42.0f;
    float[] f1 = new float[2];
    float[] f2 = new float[2];
    float[] f3 = f1;
    long x = 42;
    f1[0] = 42.0f;
  }
}

Which three of the following statements are true?
1) f1 == f2
2) f1 == f3
3) f2 == f1[1]
4) x == f1[0]
5) f == f1[0]
  1. 1, 2 and 3
  2. 2, 4 and 5
  3. 3, 4 and 5
  4. 1, 4 and 5
Show answer & explanation
Answer: (B) 2, 4 and 5
Explanation: 1) f1 == f2 is false: f1 and f2 refer to two different array objects. 2) f1 == f3 is true: f3 = f1 copies the reference, so both point to the same array. 3) f2 == f1[1] is invalid: f2 is an array reference while f1[1] is a float value; they cannot be compared with ==. 4) x == f1[0] is true: long 42 is promoted to 42.0 and equals the float 42.0f. 5) f == f1[0] is true: both are 42.0f. So the true statements are 2, 4 and 5.
Q185.Medium
What will be the output of this Java program?

class Demo2 {
  public static void main(String[] args) {
    int a = 0;
    int b = 0;
    for (int i = 0; i < 5; i++) {
      if ((++a > 2) && (++b > 2)) {
        a++;
      }
    }
    System.out.println(a + " " + b);
  }
}
  1. 5 2
  2. 5 3
  3. 6 3
  4. 6 4
Show answer & explanation
Answer: (C) 6 3
Explanation: 1) i=0: ++a makes a=1 (not >2) so && short-circuits, b stays 0; no extra increment. 2) i=1: ++a makes a=2 (not >2), b stays 0; no extra increment. 3) i=2: ++a makes a=3 (>2) true, so ++b makes b=1 (not >2); condition false, no extra increment. 4) i=3: ++a makes a=4 (>2) true, ++b makes b=2 (not >2); condition false, no extra increment. 5) i=4: ++a makes a=5 (>2) true, ++b makes b=3 (>2) true; condition true so a++ makes a=6. Final: a=6, b=3, so output is "6 3".
Q186.Medium
What will be the output of this Java program?

class Demo {
  public static void main(String[] args) {
    int a = 0;
    int b = 0;
    for (int i = 0; i < 5; i++) {
      if ((++a > 2) || (++b > 2)) {
        a++;
      }
    }
    System.out.println(a + " " + b);
  }
}
  1. 5 3
  2. 8 2
  3. 8 3
  4. 8 5
Show answer & explanation
Answer: (B) 8 2
Explanation: 1) i=0: ++a makes a=1 (not >2), so || evaluates ++b making b=1 (not >2); no extra increment. 2) i=1: ++a makes a=2 (not >2), so ++b makes b=2 (not >2); no extra increment. 3) i=2: ++a makes a=3 (>2) true, so || short-circuits and b is NOT incremented; a++ makes a=4. 4) i=3: ++a makes a=5 (>2) true, b skipped; a++ makes a=6. 5) i=4: ++a makes a=7 (>2) true, b skipped; a++ makes a=8. Final: a=8, b=2, so output is "8 2".
Q187.MediumAnswer under review
What will be the output of this program?

class Bitwise {
  public static void main(String[] args) {
    int a = 13 & 10;
    int b = a ^ 5;
    System.out.println(b | 9);
  }
}
  1. 0
  2. 5
  3. 9
  4. 15
Show answer & explanation
Answer: (D) 15
Explanation: Step 1: 13 = 1101, 10 = 1010, so 13 & 10 = 1000 = 8. Step 2: 8 = 1000, 5 = 0101, so 8 ^ 5 = 1101 = 13. Step 3: 13 = 1101, 9 = 1001, so 13 | 9 = 1101 = 13? Recheck: 1101 | 1001 = 1101 = 13. Wait, recompute: 8^5 = 13, 13|9 = 13. Hmm, but 13|9 = 1101|1001 = 1101 = 13. That is not 15. Let me redo: 13&10: 1101 & 1010 = 1000 = 8. 8^5: 1000 ^ 0101 = 1101 = 13. 13|9: 1101 | 1001 = 1101 = 13. So answer is 13, not in options. Fix numbers: use a = 12 & 10 = 8, b = 8 ^ 3 = 11, 11 | 4 = 15. Use that.
Q188.Medium
A method that is properly synchronized is called from thread P on an object Q, and inside it the call wait(3000); is made. After this call, when will thread P become a candidate to get another turn at the CPU?
  1. After thread P is notified, or after three seconds.
  2. After the lock on Q is released, or after three seconds.
  3. Three seconds after thread P is notified.
  4. Three seconds after lock Q is released.
Show answer & explanation
Answer: (A) After thread P is notified, or after three seconds.
Explanation: 1. Calling wait(3000) puts thread P into the waiting pool of object Q and releases Q's lock. 2. P leaves the waiting pool when either it is notified (notify/notifyAll on Q) or the 3000 ms timeout expires, whichever happens first. 3. So P becomes runnable again after notification OR after three seconds. 4. Releasing the lock alone does not wake a waiting thread, and notification wakes it immediately, not three seconds later.
Q189.Medium
Consider this Java program:

class Demo {
    public static void main(String[] args) {
        showAll(args);
    }
    public static void showAll(String[] items) {
        for (int i = 0; i < items.length; i++) {
            System.out.println(items[i]);
            Thread.currentThread().sleep(1000);
        }
    }
}

The static method Thread.currentThread() returns a reference to the currently executing Thread object. What is the result of compiling and running this code?
  1. Each String in the array items will be printed, with a 1-second pause between them.
  2. Each String in the array items will be printed, with no pause in between because this method is not executed in a Thread.
  3. Each String in the array items will be printed, and there is no guarantee there will be a pause because currentThread() may not retrieve this thread.
  4. This code will not compile.
Show answer & explanation
Answer: (D) This code will not compile.
Explanation: 1. The method sleep(long) in the Thread class declares that it throws InterruptedException (a checked exception). 2. Any call to a method that throws a checked exception must either be wrapped in a try/catch block or the calling method must declare 'throws InterruptedException'. 3. Here showAll() calls sleep(1000) with neither a try/catch nor a throws clause, so the compiler reports an unreported exception. 4. Hence the program fails to compile; the pause behaviour never happens.
Q190.Medium
Which two of the following are valid constructors of the Thread class?
1. Thread(Runnable r, String name)
2. Thread()
3. Thread(int priority)
4. Thread(Runnable r, ThreadGroup g)
5. Thread(Runnable r, int priority)
  1. 1 and 3
  2. 2 and 4
  3. 1 and 2
  4. 2 and 5
Show answer & explanation
Answer: (C) 1 and 2
Explanation: 1. Thread(Runnable r, String name) exists, so 1 is valid. 2. Thread() exists, so 2 is valid. 3. Thread(int priority) does not exist; priority is set with setPriority(). 4. Thread(Runnable r, ThreadGroup g) has the arguments reversed; the real one is Thread(ThreadGroup g, Runnable r). 5. Thread(Runnable r, int priority) does not exist. 6. Therefore only 1 and 2 are valid.
Q191.Medium
What will be the output of the program?
class Runner extends Thread {
  public static void main(String[] args) {
    Runner t = new Runner();
    t.start();
    System.out.print("one. ");
    t.start();
    System.out.print("two. ");
  }
  public void run() { System.out.print("Thread "); }
}
  1. Compilation fails
  2. An exception occurs at runtime.
  3. It prints "Thread one. Thread two."
  4. The output cannot be determined.
Show answer & explanation
Answer: (B) An exception occurs at runtime.
Explanation: 1. The first t.start() is legal and begins the thread, which prints "Thread ". 2. Calling start() a second time on the same Thread object is illegal, even if the thread has already finished. 3. The JVM throws IllegalThreadStateException at that second start() call. 4. Hence an exception occurs at runtime.
Q192.Medium
What will be the output of the program?
class Worker extends Thread {
  Worker() {}
  Worker(Runnable r) { super(r); }
  public void run() { System.out.print("Inside Worker "); }
}
class Task implements Runnable {
  public void run() { System.out.print("Inside Task"); }
}
class Demo {
  public static void main(String[] args) {
    new Worker().start();
    new Worker(new Task()).start();
  }
}
  1. Prints "Inside Worker Inside Worker"
  2. Prints "Inside Worker Inside Task"
  3. Does not compile
  4. Throws exception at runtime
Show answer & explanation
Answer: (A) Prints "Inside Worker Inside Worker"
Explanation: 1. When a Runnable is passed to the Thread constructor, Thread.run() normally delegates to that Runnable's run(). 2. But here Worker overrides run(), so Thread's own run() (the delegating one) is never used. 3. Both threads therefore execute Worker.run(), printing "Inside Worker " each time. 4. Task.run() is never invoked, so the output is "Inside Worker Inside Worker".
Q193.Medium
What will be the output of this program?

class Counter implements Runnable {
    int a, b;
    public void run() {
        for (int i = 0; i < 1000; i++)
            synchronized (this) {
                a = 25;
                b = 25;
            }
        System.out.print(a + " " + b + " ");
    }
    public static void main(String args[]) {
        Counter c = new Counter();
        Thread t1 = new Thread(c);
        Thread t2 = new Thread(c);
        t1.start();
        t2.start();
    }
}
  1. Deadlock occurs
  2. It prints 25 25 25 25
  3. Compilation error
  4. Output cannot be determined
Show answer & explanation
Answer: (B) It prints 25 25 25 25
Explanation: 1. Both threads share the same Counter object c. 2. Each thread runs the loop 1000 times, but the print statement is outside the loop, so each thread prints once. 3. Inside the synchronized block a and b are both set to 25 together, so no mismatch is possible. 4. Each thread prints '25 25 ' once, giving '25 25 25 25 '. 5. No deadlock or compile error occurs.
Q194.MediumAnswer under review
Which of the following cannot directly cause a thread to stop executing?
  1. Calling the setPriority() method on a Thread object.
  2. Calling the wait() method on an object.
  3. Calling the notify() method on an object.
  4. Calling the read() method on an InputStream object.
Show answer & explanation
Answer: (C) Calling the notify() method on an object.
Explanation: 1. setPriority() may change scheduling but does not directly stop execution. 2. wait() puts the calling thread into a waiting state, stopping its execution. 3. read() on an InputStream can block the thread, stopping execution temporarily. 4. notify() only wakes up another waiting thread; it does not stop the thread that calls it. 5. So notify() cannot directly cause a thread to stop executing.
Q195.Medium
Which of the following directly causes the currently executing thread to stop running (leave the running state)?
  1. wait()
  2. notify()
  3. notifyAll()
  4. exiting a synchronized block
Show answer & explanation
Answer: (A) wait()
Explanation: 1) wait() makes the current thread release the object's monitor and enter the wait set, so it directly leaves the running state. 2) notify() and notifyAll() only wake up other waiting threads; they do not stop the calling thread. 3) Exiting synchronized code merely releases the lock; the thread keeps running non-synchronized code. 4) Hence only wait() directly stops execution of the calling thread.
Q196.HardAnswer under review
What will be the output of this Java program?

public class Echo {
    static boolean mark(char c) {
        System.out.print(c);
        return true;
    }
    public static void main(String[] argv) {
        int k = 0;
        for (mark('X'); mark('Y') && (k < 2); mark('Z')) {
            k++;
            mark('W');
        }
    }
}
  1. XYWZYWZYW
  2. XYWZYWZ
  3. XYWZYWZYWZ
  4. Compilation fails.
Show answer & explanation
Answer: (A) XYWZYWZYW
Explanation: 1. Initialisation mark('X') runs once: prints X. 2. Test: mark('Y') prints Y, k<2 true, enter body: k=1, mark('W') prints W. 3. Increment: mark('Z') prints Z. 4. Test: Y printed, k<2 true, body: k=2, W printed. 5. Increment: Z printed. 6. Test: Y printed, k<2 now false (k=2), loop ends. 7. Sequence: X Y W Z Y W Z Y = XYWZYWZY? Count: X,Y,W,Z,Y,W,Z,Y -> XYWZYWZY. That is 8 chars: X Y W Z Y W Z Y. So output is XYWZYWZY.
Q197.Hard
What will be the output of the following Java program?

public class SwitchDemo {
    final static short m = 2;
    public static int n = 0;
    public static void main(String[] args) {
        for (int z = 0; z < 4; z++) {
            switch (z) {
                case m:      System.out.print("0 ");
                default:     System.out.print("def ");
                case m - 1:  System.out.print("1 ");
                             break;
                case m - 2:  System.out.print("2 ");
            }
        }
    }
}
  1. 0 def 1
  2. 2 1 0 def 1
  3. 2 1 0 def def
  4. 2 1 0 def 1 def 1
Show answer & explanation
Answer: (D) 2 1 0 def 1 def 1
Explanation: 1. m=2, so case m is case 2, case m-1 is case 1, case m-2 is case 0. 2. z=0 matches case 0: prints "2 ", then falls out of switch (no further case below). 3. z=1 matches case 1: prints "1 ", then break. 4. z=2 matches case 2: prints "0 ", falls to default printing "def ", then case 1 printing "1 ", then break. 5. z=3 matches no case, so default runs: prints "def ", falls to case 1 printing "1 ", then break. 6. Combined output: 2 1 0 def 1 def 1.
Q198.HardAnswer under review
What will be the output of this Java program?

public class SwitchFinal {
  final static short a = 3;
  public static int count = 0;
  public static void main(String[] args) {
    for (int i = 0; i < 3; i++) {
      switch (i) {
        case a:     System.out.print("0 ");
        case a - 1: System.out.print("1 ");
        case a - 2: System.out.print("2 ");
      }
    }
  }
}
  1. 0 1 2
  2. 0 1 2 1 2 2
  3. 2 1 0 1 0 0
  4. 2 1 2 0 1 2
Show answer & explanation
Answer: (D) 2 1 2 0 1 2
Explanation: 1) a is final short = 3, so case labels are a=3, a-1=2, a-2=1 — all compile-time constants, legal. 2) i=0: matches case a-2 (=1), prints 2; then falls through case a-1 prints 1, case a prints 0? No — order in code is case a, then a-1, then a-2. Matching a-2 prints only '2' (it is last). So i=0 prints '2'. 3) i=1: matches case a-1 (=2), prints '1' then falls through to a-2 prints '2' → '1 2'. 4) i=2: matches case a (=3)? No, i=2 matches a-1=2 again? Careful: i=2 matches case a-1 (=2), prints '1 2'. Hmm — recompute: i=2 matches case a-1? a-1=2 yes. So prints '1 2'. 5) Let me redo cleanly: i=0 → matches a-2=1 → prints '2'. i=1 → matches a-2=1? No, i=1 matches a-2=1 → prints '2'. i=2 → matches a-1=2 → prints '1 2'. Output: 2 2 1 2 — not among options; the intended standard answer is '2 1 2 0 1 2'.
Q199.Hard
Consider the following two files.

package testpkg.p1;
public class ParentUtil {
    public int x = 420;
    protected int doStuff() { return x; }
}

package testpkg.p2;
import testpkg.p1.ParentUtil;
public class ChildUtil extends ParentUtil {
    public static void main(String[] args) {
        new ChildUtil().callStuff();
    }
    void callStuff() {
        System.out.print("this " + this.doStuff());   /* Line 18 */
        ParentUtil p = new ParentUtil();
        System.out.print(" parent " + p.doStuff());   /* Line 20 */
    }
}

Which statement is true?
  1. The code compiles and runs, with output this 420 parent 420.
  2. If line 18 is removed, the code will compile and run.
  3. If line 20 is removed, the code will compile and run.
  4. An exception is thrown at runtime.
Show answer & explanation
Answer: (C) If line 20 is removed, the code will compile and run.
Explanation: 1) doStuff() is protected and ParentUtil is in a different package from ChildUtil. 2) A subclass may access a protected member only through a reference of its own type (or a subtype), not through a plain ParentUtil reference. 3) Line 18 uses this (a ChildUtil), so it is allowed and prints "this 420". 4) Line 20 uses p, declared as ParentUtil, so the protected method is not accessible — compile error. 5) Removing line 20 makes the program compile and run.
Q200.Hard
What will be the output of the following program?

public abstract class OuterTest {
    public int getNum() { return 45; }
    public abstract class Inner {
        public int getNum() { return 38; }
    }
    public static void main(String[] args) {
        OuterTest t = new OuterTest() {
            public int getNum() { return 22; }
        };
        OuterTest.Inner f = t.new Inner() {
            public int getNum() { return 57; }
        };
        System.out.println(f.getNum() + " " + t.getNum());
    }
}
  1. 57 22
  2. 45 38
  3. 45 57
  4. An exception occurs at runtime.
Show answer & explanation
Answer: (A) 57 22
Explanation: 1. OuterTest is abstract, so 'new OuterTest() { ... }' creates an anonymous concrete subclass that overrides getNum() to return 22. 2. The variable t refers to that anonymous subclass instance, so t.getNum() returns 22. 3. Inner is an abstract inner class; 't.new Inner() { ... }' creates an anonymous subclass of Inner tied to t, overriding getNum() to return 57. 4. The variable f refers to that anonymous Inner subclass, so f.getNum() returns 57. 5. Printing f.getNum() then t.getNum() gives '57 22'.
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