Certainly! Here are 100 high-quality, complex multiple-choice questions on Java Object-Oriented Programming (OOP) concepts, along with answers and explanations, to help you prepare for technical interviews at top tech companies.


Question 1

Topic: Advanced Inheritance and Overriding

Consider the following code:

class Animal {
    public void eat() throws IOException {
        System.out.println("Animal eats");
    }
}
 
class Dog extends Animal {
    public void eat() throws FileNotFoundException {
        System.out.println("Dog eats");
    }
}

Which statement is true regarding the eat() method in the Dog class?

A. It is not valid because FileNotFoundException is a checked exception.
B. It is valid because FileNotFoundException is a subclass of IOException.
C. It is not valid because a subclass method cannot throw any exceptions if the superclass method doesn’t.
D. It is valid only if eat() in Animal does not throw any exception.

Answer: B. It is valid because FileNotFoundException is a subclass of IOException.

Explanation: In method overriding, the subclass method can throw the same exceptions or subclasses of those exceptions declared in the superclass method. FileNotFoundException is a subclass of IOException, so it’s acceptable.


Question 2

Topic: Polymorphism and Method Overloading

Given the following classes:

class Shape {
    public void draw(Object obj) {
        System.out.println("Shape: Drawing with Object");
    }
}
 
class Circle extends Shape {
    public void draw(String str) {
        System.out.println("Circle: Drawing with String");
    }
}
 
public class Test {
    public static void main(String[] args) {
        Shape s = new Circle();
        s.draw("Hello");
    }
}

What will be the output when Test is run?

A. Shape: Drawing with Object
B. Circle: Drawing with String
C. Compilation error due to ambiguity
D. Runtime error

Answer: A. Shape: Drawing with Object

Explanation: The draw(String str) method in Circle is an overload, not an override. Since the reference type is Shape, and Shape doesn’t have a draw(String) method, the draw(Object obj) method in Shape is called.


Question 3

Topic: Abstract Classes and Interfaces

Which of the following statements is true regarding abstract classes and interfaces in Java?

A. An abstract class can implement an interface without providing implementations for all its methods.
B. An interface can extend an abstract class.
C. An abstract class cannot have a constructor.
D. A class can inherit from multiple abstract classes.

Answer: A. An abstract class can implement an interface without providing implementations for all its methods.

Explanation: Abstract classes can implement interfaces and are not required to implement all the interface methods because they are abstract and can leave the implementation to subclasses.


Question 4

Topic: Static and Instance Variables

Consider the following code:

public class Counter {
    private static int count = 0;
 
    public Counter() {
        count++;
    }
 
    public int getCount() {
        return count;
    }
 
    public static void main(String[] args) {
        Counter c1 = new Counter();
        Counter c2 = new Counter();
        System.out.println(c2.getCount());
    }
}

What will be the output?

A. 1
B. 2
C. 0
D. Compilation error

Answer: B. 2

Explanation: The count variable is static; it is shared among all instances. Each time the constructor is called, it increments count. After creating two instances, count becomes 2.


Question 5

Topic: Enums and OOP

Which of the following is true about enums in Java?

A. Enums can extend other classes.
B. Enums can implement interfaces.
C. Enums cannot have methods.
D. Enums are not type-safe.

Answer: B. Enums can implement interfaces.

Explanation: Enums can implement interfaces but cannot extend classes because they implicitly extend java.lang.Enum. Enums are type-safe and can include methods.


Question 6

Topic: Generics and Wildcards

Given the following method:

public void addToList(List<? super Integer> list) {
    list.add(new Integer(100));
}

Which of the following statements is true?

A. The method can add any type of Number to the list.
B. The method can add any type of Object to the list.
C. The method can only add Integer objects to the list.
D. The method cannot add any elements to the list.

Answer: C. The method can only add Integer objects to the list.

Explanation: The lower bounded wildcard ? super Integer allows Integer and its supertypes. However, you can safely add Integer instances to the list, but not other supertypes like Number or Object.


Question 7

Topic: Exception Handling and OOP

Given the following code:

class Base {
    void foo() throws Exception {
        System.out.println("Base foo");
    }
}
 
class Derived extends Base {
    void foo() {
        System.out.println("Derived foo");
    }
}

What happens if you try to compile this code?

A. It compiles successfully.
B. Compilation error because the overridden method does not throw an exception.
C. Compilation error because the overridden method must throw the same exception.
D. Runtime exception occurs when foo() is called.

Answer: A. It compiles successfully.

Explanation: In method overriding, the subclass method cannot throw broader checked exceptions than the superclass method, but it can throw fewer or none. So, omitting the exception is acceptable.


Question 8

Topic: Anonymous Inner Classes

What is the result of executing the following code?

interface Greeting {
    String greet();
}
 
public class Test {
    public static void main(String[] args) {
        Greeting g = new Greeting() {
            public String greet() {
                return "Hello";
            }
        };
        System.out.println(g.greet());
    }
}

A. It prints Hello.
B. It prints nothing.
C. Compilation error due to incorrect syntax of anonymous class.
D. Compilation error because interfaces cannot be instantiated.

Answer: A. It prints Hello.

Explanation: An anonymous inner class is created that implements the Greeting interface, and the greet() method returns "Hello".


Question 9

Topic: Covariant Return Types

Consider the code:

class SuperClass {
    SuperClass getInstance() {
        return this;
    }
}
 
class SubClass extends SuperClass {
    @Override
    SubClass getInstance() {
        return this;
    }
}

Which statement is true?

A. The code will not compile because of invalid return type.
B. The code compiles but throws a runtime exception.
C. The code compiles successfully due to covariant return types.
D. Method overriding cannot change the return type.

Answer: C. The code compiles successfully due to covariant return types.

Explanation: Java allows overriding methods to return a subtype of the return type declared in the superclass’s method (covariant return types).


Question 10

Topic: Reflection API

Which class is used to obtain information about an object’s class at runtime in Java?

A. java.lang.Class
B. java.lang.Object
C. java.lang.Runtime
D. java.lang.reflect.Method

Answer: A. java.lang.Class

Explanation: The Class class represents classes and interfaces at runtime and is used in the Reflection API to obtain class information.


Question 11

Topic: Immutable Objects

Which of the following statements is true regarding immutability in Java?

A. Immutable objects can have their fields modified after creation.
B. String is an immutable class.
C. Immutable objects provide no benefits in concurrent programming.
D. All wrapper classes are mutable.

Answer: B. String is an immutable class.

Explanation: The String class is immutable in Java. Once created, its value cannot be changed. This immutability helps in concurrent programming by avoiding synchronization issues.


Question 12

Topic: Access Modifiers and Inheritance

Given:

package packageA;
public class ClassA {
    protected void display() {
        System.out.println("ClassA");
    }
}
package packageB;
import packageA.ClassA;
 
public class ClassB extends ClassA {
    public static void main(String[] args) {
        ClassA obj = new ClassB();
        obj.display();
    }
}

What will happen when you compile and run ClassB?

A. It prints ClassA.
B. Compilation error because display() is not accessible.
C. Runtime error due to illegal access.
D. Compilation error due to package issues.

Answer: B. Compilation error because display() is not accessible.

Explanation: The display() method is protected. When accessed through a reference of ClassA outside its package, it is not accessible. It must be accessed through a subclass reference.


Question 13

Topic: Multithreading and Synchronization

Which of the following statements is true?

A. The synchronized keyword can be applied to variables.
B. Static synchronized methods lock on the class object.
C. The wait() method must be called from a static context.
D. A thread cannot hold multiple locks at the same time.

Answer: B. Static synchronized methods lock on the class object.

Explanation: Static synchronized methods synchronize on the Class object associated with the class.


Question 14

Topic: Method Overriding and Exception Handling

Given the code:

class Parent {
    void show() {
        System.out.println("Parent show");
    }
}
 
class Child extends Parent {
    void show() throws IOException {
        System.out.println("Child show");
    }
}

What happens when compiling the Child class?

A. Compiles successfully.
B. Compilation error due to incompatible exceptions.
C. Compilation error due to method signature mismatch.
D. Runtime exception occurs when show() is called.

Answer: B. Compilation error due to incompatible exceptions.

Explanation: The overriding method cannot declare a checked exception if the overridden method does not declare it.


Question 15

Topic: Static Blocks and Initialization

Consider the code:

class Initialization {
    static int value = 0;
 
    static {
        value = 10;
        System.out.println("Static block");
    }
 
    public Initialization() {
        System.out.println("Constructor");
    }
 
    public static void main(String[] args) {
        Initialization obj = new Initialization();
        System.out.println(value);
    }
}

What is the output when Initialization is executed?

A.

Static block
Constructor
10

B.

Constructor
Static block
10

C.

Static block
Constructor
0

D.

Constructor
0
Static block

Answer: A.

Static block
Constructor
10

Explanation: Static blocks are executed when the class is first loaded. The static block sets value to 10. Then the constructor is called, and finally, value is printed.


Question 16

Topic: Interfaces and Default Methods

Which of the following is true about default methods in interfaces?

A. They can override methods from java.lang.Object.
B. A class implementing an interface with a default method must override it.
C. Default methods cannot be static.
D. They allow interfaces to have method implementations.

Answer: D. They allow interfaces to have method implementations.

Explanation: Default methods provide method bodies in interfaces, allowing them to have implementations.


Question 17

Topic: Static Import

What is the purpose of static import in Java?

A. To import static nested classes from another class.
B. To import static methods and variables so they can be used without class qualification.
C. To import classes from packages statically at runtime.
D. There is no such feature in Java.

Answer: B. To import static methods and variables so they can be used without class qualification.

Explanation: Static import allows you to access static members of a class directly without class qualification.


Question 18

Topic: Composition vs. Inheritance

Which of the following statements is true regarding composition and inheritance?

A. Composition is preferred over inheritance for code reuse.
B. Inheritance allows for more flexibility than composition.
C. Composition models an IS-A relationship.
D. Inheritance models a HAS-A relationship.

Answer: A. Composition is preferred over inheritance for code reuse.

Explanation: Composition (HAS-A relationship) is often preferred because it provides better encapsulation and flexibility compared to inheritance (IS-A relationship).


Question 19

Topic: Annotations and Reflection

Which annotation is not available at runtime via reflection?

A. @Override
B. @Deprecated
C. @SuppressWarnings
D. @Retention(RetentionPolicy.RUNTIME)

Answer: C. @SuppressWarnings

Explanation: @SuppressWarnings has a retention policy of SOURCE, so it is discarded by the compiler and not available at runtime.


Question 20

Topic: Serialization and transient Keyword

What is the effect of declaring an instance variable as transient?

A. It cannot be modified.
B. It will not be serialized.
C. It is shared across all instances of the class.
D. It is read-only.

Answer: B. It will not be serialized.

Explanation: The transient keyword indicates that the variable should not be included in the serialization process.


Question 21

Topic: Class Loaders

Which of the following is true about class loaders in Java?

A. Bootstrap class loader can be overridden by user-defined class loaders.
B. Each class loader has its own namespace.
C. Class loaders are used only for loading classes from the local file system.
D. Garbage collection does not apply to class loaders.

Answer: B. Each class loader has its own namespace.

Explanation: Class loaders define namespaces that determine how classes are loaded and managed.


Question 22

Topic: Method References and Lambdas

Given the following code:

interface Printer {
    void print(String s);
}
 
public class Test {
    public static void main(String[] args) {
        Printer p = System.out::println;
        p.print("Hello World");
    }
}

What will be the output?

A. Compilation error due to invalid method reference.
B. Hello World
C. Runtime error due to null reference.
D. No output.

Answer: B. Hello World

Explanation: The method reference System.out::println is valid and refers to the println method. It prints “Hello World”.


Question 23

Topic: Anonymous Classes and Scope

What is the output of the following code?

public class Test {
    private String message = "Outer";
 
    public void display() {
        Runnable r = new Runnable() {
            private String message = "Inner";
 
            public void run() {
                System.out.println(this.message);
            }
        };
        r.run();
    }
 
    public static void main(String[] args) {
        new Test().display();
    }
}

A. Outer
B. Inner
C. Compilation error
D. Runtime exception

Answer: B. Inner

Explanation: The this reference inside the anonymous class refers to the anonymous class instance, so this.message is “Inner”.


Question 24

Topic: Threads and wait()/notify()

Which of the following statements is true regarding wait() and notify() methods?

A. They are defined in the Thread class.
B. They can be called without owning the object’s monitor.
C. wait() causes the thread to release the object’s lock.
D. notify() wakes up all waiting threads.

Answer: C. wait() causes the thread to release the object’s lock.

Explanation: When a thread calls wait(), it releases the lock and waits until it’s notified.


Question 25

Topic: Immutable Classes

Which set of statements best defines an immutable class in Java?

A. Class is declared as final, all fields are private, and there are no setters.
B. All methods are static, and all fields are final.
C. Class is abstract, and all fields are protected.
D. Class has only public fields and no methods.

Answer: A. Class is declared as final, all fields are private, and there are no setters.

Explanation: An immutable class cannot be extended (final class), fields cannot be modified (private and final), and no setters are provided.


Question 26

Topic: Overloading vs. Overriding

Which of the following statements is true?

A. Overloading methods must have different names.
B. Overriding methods must have the same return type or a subtype (covariant return).
C. Overloading is determined at runtime.
D. Overriding methods can reduce the visibility of the superclass method.

Answer: B. Overriding methods must have the same return type or a subtype (covariant return).

Explanation: Overriding methods must have the same name, parameter list, and return type (or covariant subtype). Overloading is determined at compile-time.


Question 27

Topic: Java Memory Model and volatile

What does the volatile keyword guarantee in Java?

A. Atomicity of operations on a variable.
B. Visibility of changes to variables across threads.
C. Ordering of reads and writes to variables within a thread.
D. That multiple threads cannot access the variable simultaneously.

Answer: B. Visibility of changes to variables across threads.

Explanation: volatile ensures that reads and writes to a variable are directly from and to main memory, making changes visible to all threads.


Question 28

Topic: Finalization and Garbage Collection

Which of the following statements is true?

A. The finalize() method is guaranteed to be called by the garbage collector.
B. Calling System.gc() forces garbage collection immediately.
C. Objects are eligible for garbage collection when there are no more references to them.
D. You can predict the order in which objects are garbage collected.

Answer: C. Objects are eligible for garbage collection when there are no more references to them.

Explanation: When an object is no longer reachable, it becomes eligible for garbage collection. There’s no guarantee or predictability about when it will happen.


Question 29

Topic: Multiple Inheritance and Interfaces

Which of the following is true regarding interfaces and multiple inheritance?

A. A class can implement multiple interfaces.
B. A class can extend multiple classes.
C. Interfaces cannot extend other interfaces.
D. Interfaces can contain constructors.

Answer: A. A class can implement multiple interfaces.

Explanation: Java supports multiple inheritance through interfaces; a class can implement multiple interfaces.


Question 30

Topic: java.lang.Object Methods

Which method from java.lang.Object class is used to create a copy of an object?

A. clone()
B. copy()
C. duplicate()
D. replicate()

Answer: A. clone()

Explanation: The clone() method is used to create and return a copy of the object.

Certainly! Here are the remaining questions (31 to 100) on advanced Java Object-Oriented Programming (OOP) concepts, complete with answers and explanations, to help you prepare for high-level technical interviews.


Question 31

Topic: Generics and Type Erasure

Which statement is true about Java generics and type erasure?

A. Generics are implemented at runtime, preserving type information.
B. Type parameters are replaced with their bounds or Object during compilation.
C. Generics allow for primitive types as type parameters.
D. Type erasure removes the need for type casting.

Answer: B. Type parameters are replaced with their bounds or Object during compilation.

Explanation: Java implements generics through type erasure, where type parameters are replaced with their bounds (or Object if unbounded) at compile time. Type information is not preserved at runtime.


Question 32

Topic: equals() and hashCode() Contract

Which of the following statements is false regarding the equals() and hashCode() methods?

A. If two objects are equal according to equals(), they must have the same hashCode().
B. Two objects with the same hashCode() are always equal according to equals().
C. Overriding equals() requires overriding hashCode().
D. Violating the equals() and hashCode() contract can cause issues in collections like HashMap.

Answer: B. Two objects with the same hashCode() are always equal according to equals().

Explanation: Two objects can have the same hashCode() but not be equal according to equals(). This is known as a hash collision.


Question 33

Topic: Inner Classes and Scopes

What is the output of the following code?

public class Outer {
    private int x = 10;
 
    class Inner {
        private int x = 20;
 
        void print() {
            int x = 30;
            System.out.println(x);          // Line 1
            System.out.println(this.x);     // Line 2
            System.out.println(Outer.this.x); // Line 3
        }
    }
 
    public static void main(String[] args) {
        Outer.Inner obj = new Outer().new Inner();
        obj.print();
    }
}

A.

30
20
10

B.

10
20
30

C.

30
10
20

D.

20
30
10

Answer: A.

30
20
10

Explanation: Variable x at Line 1 refers to the local variable (30). this.x refers to the x of the Inner class (20). Outer.this.x refers to the x of the Outer class (10).


Question 34

Topic: Method Hiding

Consider the following code:

class SuperClass {
    static void display() {
        System.out.println("SuperClass");
    }
}
 
class SubClass extends SuperClass {
    static void display() {
        System.out.println("SubClass");
    }
}
 
public class Test {
    public static void main(String[] args) {
        SuperClass obj = new SubClass();
        obj.display();
    }
}

What will be the output?

A. SuperClass
B. SubClass
C. Compilation error
D. Runtime exception

Answer: A. SuperClass

Explanation: Static methods are not overridden but hidden. The method called is determined by the reference type (SuperClass), so SuperClass.display() is called.


Question 35

Topic: Design Patterns - Singleton

Which of the following implementations correctly creates a thread-safe Singleton in Java?

A.

public class Singleton {
    private static Singleton instance;
 
    private Singleton() {}
 
    public static Singleton getInstance() {
        if(instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
}

B.

public class Singleton {
    private static Singleton instance = new Singleton();
 
    private Singleton() {}
 
    public static synchronized Singleton getInstance() {
        return instance;
    }
}

C.

public class Singleton {
    private static volatile Singleton instance;
 
    private Singleton() {}
 
    public static Singleton getInstance() {
        if(instance == null) {
            synchronized(Singleton.class) {
                if(instance == null) {
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
}

D.

public enum Singleton {
    INSTANCE;
}

Answer: D.

public enum Singleton {
    INSTANCE;
}

Explanation: Using an enum to implement Singleton is the best practice as it handles serialization and thread safety automatically.


Question 36

Topic: Functional Interfaces and Lambda Expressions

Which of the following is a functional interface in Java?

A. Comparator<T>
B. Serializable
C. Runnable
D. Both A and C

Answer: D. Both A and C

Explanation: Both Comparator and Runnable are functional interfaces because they have exactly one abstract method.


Question 37

Topic: super and this Keywords

What does the super keyword represent in Java?

A. A reference to the superclass of the current object
B. A reference to the current object
C. A way to call methods from the subclass
D. A way to access private members of another class

Answer: A. A reference to the superclass of the current object

Explanation: super is used to access methods and constructors of the superclass.


Question 38

Topic: Overriding final Methods

Consider the code:

class Parent {
    public final void display() {
        System.out.println("Parent");
    }
}
 
class Child extends Parent {
    public void display() {
        System.out.println("Child");
    }
}

What will happen when compiling this code?

A. Compiles successfully
B. Compilation error due to overriding a final method
C. The Child class display() hides the Parent class method
D. Runtime exception

Answer: B. Compilation error due to overriding a final method

Explanation: You cannot override a final method in a subclass.


Question 39

Topic: Copy Constructors

Does Java support copy constructors like C++?

A. Yes, Java provides a default copy constructor
B. No, but you can create your own copy constructor
C. No, and you cannot implement a copy constructor in Java
D. Yes, but only for primitive types

Answer: B. No, but you can create your own copy constructor

Explanation: Java doesn’t have a built-in copy constructor, but you can define one manually in your class.


Question 40

Topic: Abstract Classes and Constructors

Which statement is true?

A. Abstract classes cannot have constructors
B. Abstract classes can have constructors, which are called when a subclass is instantiated
C. You can instantiate an abstract class directly using its constructor
D. Abstract class constructors cannot take parameters

Answer: B. Abstract classes can have constructors, which are called when a subclass is instantiated

Explanation: Although you cannot instantiate an abstract class directly, its constructor is called when a concrete subclass is instantiated.


Question 41

Topic: Streams and Functional Programming

What does the following code output?

List<String> list = Arrays.asList("apple", "banana", "cherry");
list.stream()
    .filter(s -> s.startsWith("b"))
    .forEach(System.out::println);

A.

apple
banana
cherry

B.

banana

C.

apple

D. No output

Answer: B.

banana

Explanation: The filter() method filters elements that start with “b”; in this case, only “banana”.


Question 42

Topic: Method References with Constructors

Which of the following is a correct use of a constructor method reference?

A.

Supplier<Person> supplier = Person:new;

B.

Supplier<Person> supplier = Person::new;

C.

Supplier<Person> supplier = new Person();

D.

Person supplier = Person::new;

Answer: B.

Supplier<Person> supplier = Person::new;

Explanation: The correct syntax for a constructor method reference is ClassName::new.


Question 43

Topic: Modules (Java 9+)

Which of the following statements is true about Java modules?

A. Every JAR file is a module
B. Modules are declared using a module-info.java file
C. Modules cannot specify which packages they export
D. Modules are only used for dependency injection

Answer: B. Modules are declared using a module-info.java file

Explanation: The module-info.java file is used to declare a module and its dependencies.


Question 44

Topic: Weak References and Garbage Collection

What is the primary use of a WeakReference in Java?

A. To prevent an object from being garbage collected
B. To allow an object to be garbage collected while still allowing it to be referenced
C. To create a strong reference to an object
D. To facilitate multithreading

Answer: B. To allow an object to be garbage collected while still allowing it to be referenced

Explanation: WeakReference allows the referenced object to be garbage collected if no strong references exist.


Question 45

Topic: Serialization UID

Why is serialVersionUID important in Java serialization?

A. It specifies the version of the JVM to use for serialization
B. It ensures that a deserialized object matches the serialized version
C. It prevents serialization of certain fields
D. It is required for all classes, serializable or not

Answer: B. It ensures that a deserialized object matches the serialized version

Explanation: serialVersionUID is used to verify that the sender and receiver of a serialized object have loaded classes that are compatible with respect to serialization.


Question 46

Topic: Method Overriding with Covariant Return Types

Given:

class Animal {
    Animal getInstance() {
        return new Animal();
    }
}
 
class Dog extends Animal {
    @Override
    Dog getInstance() {
        return new Dog();
    }
}

What is the term for changing the return type in this way?

A. Return type overloading
B. Covariant return types
C. Method hiding
D. Contravariant return types

Answer: B. Covariant return types

Explanation: Covariant return types allow an overriding method to return a subtype of the type returned by the overridden method.


Question 47

Topic: Java Memory Model - Stack vs. Heap

Which of the following statements is true?

A. Instance variables are stored in the stack
B. Local variables are stored in the heap
C. Object instances are stored in the heap
D. The stack and heap are the same in Java

Answer: C. Object instances are stored in the heap

Explanation: Objects and their instance variables reside in the heap, while local variables and method call information are stored in the stack.


Question 48

Topic: IllegalArgumentException vs. IllegalStateException

What is the primary difference between IllegalArgumentException and IllegalStateException?

A. IllegalArgumentException is checked; IllegalStateException is unchecked
B. IllegalArgumentException indicates wrong arguments passed; IllegalStateException indicates inappropriate state
C. They are the same and can be used interchangeably
D. They represent errors during compilation

Answer: B. IllegalArgumentException indicates wrong arguments passed; IllegalStateException indicates inappropriate state

Explanation: Use IllegalArgumentException when the method receives inappropriate arguments; use IllegalStateException when the object is not in an appropriate state.


Question 49

Topic: Default Methods and Multiple Inheritance

What happens when a class implements two interfaces that have default methods with the same signature?

A. Compilation error due to ambiguity
B. The class inherits the method from the first interface
C. The class must override the method
D. The JVM randomly picks one of the methods

Answer: C. The class must override the method

Explanation: The class must provide an implementation to resolve the conflict between the two default methods.


Question 50

Topic: Exception Hierarchy

Which of the following is a direct subclass of Exception but not a RuntimeException?

A. NullPointerException
B. IOException
C. ClassCastException
D. IndexOutOfBoundsException

Answer: B. IOException

Explanation: IOException is a checked exception and directly extends Exception.


Question 51

Topic: ClassNotFoundException vs. NoClassDefFoundError

What is the difference between ClassNotFoundException and NoClassDefFoundError?

A. Both are the same and used interchangeably
B. ClassNotFoundException is a checked exception; NoClassDefFoundError is an error
C. NoClassDefFoundError occurs when the class path is incorrect; ClassNotFoundException occurs at runtime
D. ClassNotFoundException is thrown by the compiler; NoClassDefFoundError is thrown by the JVM

Answer: B. ClassNotFoundException is a checked exception; NoClassDefFoundError is an error

Explanation: ClassNotFoundException occurs when an application tries to load a class at runtime using Class.forName and the class is not found. NoClassDefFoundError is thrown when the JVM or a classloader cannot find the class definition.


Question 52

Topic: Immutable Collections

Which method can be used to create an immutable list in Java?

A. Arrays.asList("a", "b", "c")
B. List.of("a", "b", "c")
C. new ArrayList<>(Arrays.asList("a", "b", "c"))
D. Collections.emptyList()

Answer: B. List.of("a", "b", "c")

Explanation: List.of() creates an immutable list (added in Java 9). Arrays.asList() creates a fixed-size, mutable list.


Question 53

Topic: Optional Class

What is the purpose of the Optional class in Java?

A. To allow null values in collections
B. To represent a value that may be present or absent, avoiding null
C. To enable optional parameters in methods
D. To enforce non-null values

Answer: B. To represent a value that may be present or absent, avoiding null

Explanation: Optional is used to express potential absence of a value and to avoid NullPointerException.


Question 54

Topic: Double-Checked Locking

Why is the volatile keyword used in the double-checked locking idiom?

A. To ensure visibility of changes to variables across threads
B. To make the variable immutable
C. To prevent reordering of instructions
D. Both A and C

Answer: D. Both A and C

Explanation: volatile ensures visibility and prevents instruction reordering, which is essential in double-checked locking.


Question 55

Topic: Enum Constructors

Which of the following is true about enum constructors in Java?

A. Enum constructors can be public
B. Enum constructors can be private or default
C. Enum constructors can be overloaded
D. Both B and C

Answer: D. Both B and C

Explanation: Enum constructors are implicitly private and can be overloaded.


Question 56

Topic: Class Design Principles

Which of the following principles is represented by “Program to an interface, not an implementation”?

A. Open/Closed Principle
B. Dependency Inversion Principle
C. Liskov Substitution Principle
D. Interface Segregation Principle

Answer: B. Dependency Inversion Principle

Explanation: The Dependency Inversion Principle suggests depending on abstractions (interfaces) rather than concrete implementations.


Question 57

Topic: Bridge Method in Generics

What is a bridge method in Java generics?

A. A method used to connect two unrelated classes
B. A compiler-generated method to preserve polymorphism with generics
C. A method used in networking for socket communication
D. An interface method that must be overridden

Answer: B. A compiler-generated method to preserve polymorphism with generics

Explanation: Bridge methods are synthetic methods created by the compiler to ensure that subtype substitutability works with type-erased generics.


Question 58

Topic: Universal Generics

Why can’t you create an instance of a generic type parameter T directly in Java?

A. Because of type erasure, the actual type T is not known at runtime
B. Java doesn’t allow instantiation of any objects in generics
C. You can instantiate T if it has a default constructor
D. It’s possible by passing Class<T> and using reflection

Answer: A. Because of type erasure, the actual type T is not known at runtime

Explanation: Due to type erasure, T is replaced with its bound (or Object), so you cannot instantiate it directly.


Question 59

Topic: Iterator vs. Enumeration

Which of the following is false about Iterator and Enumeration?

A. Both can be used to traverse collections
B. Iterator allows removal of elements during iteration
C. Enumeration has hasNext() and next() methods
D. Iterator is preferred over Enumeration in Java Collections Framework

Answer: C. Enumeration has hasNext() and next() methods

Explanation: Enumeration has hasMoreElements() and nextElement() methods, not hasNext() and next().


Question 60

Topic: Design Patterns - Factory Method

Which of the following best describes the Factory Method pattern?

A. It defines an interface for creating an object but lets subclasses alter the type of objects that will be created
B. It provides a way to access the elements of an aggregate object sequentially
C. It allows an object to alter its behavior when its internal state changes
D. It composes objects into tree structures to represent part-whole hierarchies

Answer: A. It defines an interface for creating an object but lets subclasses alter the type of objects that will be created

Explanation: The Factory Method pattern delegates the creation of objects to subclasses.


Question 61

Topic: Class Cast Exception

Given:

Object obj = new Integer(10);
String str = (String) obj;

What will happen at runtime?

A. str will contain "10"
B. ClassCastException is thrown
C. The integer 10 is automatically converted to a string
D. Compilation error

Answer: B. ClassCastException is thrown

Explanation: Casting an Integer to String is invalid and will cause a ClassCastException.


Question 62

Topic: JDBC and OOP

Which JDBC driver type is a pure Java driver that implements the network protocol for a specific DBMS?

A. Type 1
B. Type 2
C. Type 3
D. Type 4

Answer: D. Type 4

Explanation: Type 4 drivers are pure Java drivers that communicate directly with a DBMS server over a network.


Question 63

Topic: Final Parameters

What does declaring a method parameter as final do?

A. Prevents the parameter from being modified within the method
B. Prevents the method from being overridden
C. Makes the parameter accessible globally
D. Allows the parameter to be modified by inner classes

Answer: A. Prevents the parameter from being modified within the method

Explanation: Declaring a parameter as final means it cannot be reassigned within the method.


Question 64

Topic: Generics - Bounded Type Parameters

Which is the correct way to declare a generic method that accepts any Number subtype?

A.

public <T> void method(T param) {}

B.

public <T extends Number> void method(T param) {}

C.

public <T super Number> void method(T param) {}

D.

public <Number> void method(Number param) {}

Answer: B.

public <T extends Number> void method(T param) {}

Explanation: This syntax bounds the type parameter T to Number and its subclasses.


Question 65

Topic: Serialization and Externalizable

Which of the following is true about the Externalizable interface?

A. It extends Serializable and allows control over serialization
B. It requires implementing writeObject() and readObject() methods
C. It serializes objects automatically like Serializable
D. It is used to serialize external resources

Answer: A. It extends Serializable and allows control over serialization

Explanation: By implementing Externalizable, you can control the serialization by implementing writeExternal() and readExternal() methods.


Question 66

Topic: Design Patterns - Observer

Which of the following best describes the Observer pattern?

A. Defines a one-to-many dependency between objects so that when one object changes state, all its dependents are notified
B. Encapsulates a request as an object, thereby letting you parameterize clients with different requests
C. Provides a surrogate or placeholder for another object to control access to it
D. Separates the construction of a complex object from its representation

Answer: A. Defines a one-to-many dependency between objects so that when one object changes state, all its dependents are notified

Explanation: The Observer pattern allows objects to subscribe to events and get notified of changes.


Question 67

Topic: Java Collections - Map Ordering

Which Map implementation should you use if you want to maintain insertion order?

A. HashMap
B. TreeMap
C. LinkedHashMap
D. ConcurrentHashMap

Answer: C. LinkedHashMap

Explanation: LinkedHashMap maintains insertion order.


Question 68

Topic: Compare == and equals()

Which statement is true about the == operator and equals() method when comparing objects?

A. == checks for value equality; equals() checks for reference equality
B. == checks for reference equality; equals() checks for value equality
C. Both == and equals() check for value equality
D. Both == and equals() check for reference equality

Answer: B. == checks for reference equality; equals() checks for value equality

Explanation: == checks if two references point to the same object; equals() is meant to check if two objects are logically equal.


Question 69

Topic: Exception Propagation

What happens if a checked exception is not caught or declared to be thrown?

A. The program compiles successfully
B. The compiler throws an error
C. The exception is converted to an unchecked exception
D. The JVM handles the exception automatically

Answer: B. The compiler throws an error

Explanation: Checked exceptions must be either caught or declared in the method signature; otherwise, the code will not compile.


Question 70

Topic: Generics - Wildcards

What does the wildcard ? extends Number signify in Java generics?

A. The unknown type is a superclass of Number
B. The unknown type is Number or any of its subclasses
C. It allows adding any type of Number to the collection
D. It restricts the collection to exactly Number type

Answer: B. The unknown type is Number or any of its subclasses

Explanation: ? extends Number accepts Number and any subclass of Number.


Question 71

Topic: Concurrent Collections

Which collection is thread-safe without using synchronization explicitly?

A. ArrayList
B. Vector
C. LinkedList
D. HashSet

Answer: B. Vector

Explanation: Vector is synchronized internally and is thread-safe.


Question 72

Topic: Immutable Classes and Inheritance

Why is it recommended to declare immutable classes as final?

A. To prevent subclassing which might compromise immutability
B. To improve performance
C. To allow method overloading
D. It is not necessary to declare them as final

Answer: A. To prevent subclassing which might compromise immutability

Explanation: Declaring the class as final prevents others from extending it and potentially adding mutable behavior.


Question 73

Topic: Thread Priority

Which statement is true about thread priority in Java?

A. Higher priority threads always execute before lower priority threads
B. Thread priority guarantees the order of execution
C. Thread priority is platform-dependent and may not work as expected
D. All threads have the same default priority that cannot be changed

Answer: C. Thread priority is platform-dependent and may not work as expected

Explanation: Thread scheduling and priority handling are dependent on the JVM and underlying OS.


Question 74

Topic: Reflection API - Access Private Fields

Can you modify a private field of a class using reflection?

A. No, private fields are inaccessible via reflection
B. Yes, by setting the field’s accessibility to true
C. Only if the class has a public setter
D. Only in the same package

Answer: B. Yes, by setting the field’s accessibility to true

Explanation: You can access and modify private fields by calling setAccessible(true) on the Field object.


Question 75

Topic: Method Overloading and Autoboxing

Given the following methods:

void method(int i) { }
void method(Integer i) { }
void method(long l) { }

Which method is called when method(5) is invoked?

A. void method(int i)
B. void method(Integer i)
C. void method(long l)
D. Compilation error due to ambiguity

Answer: A. void method(int i)

Explanation: Exact type match is preferred over autoboxing or widening conversions.


Question 76

Topic: Designing hashCode() and equals()

Which of the following is good practice when overriding equals() and hashCode()?

A. Only override equals() and leave hashCode() as is
B. Use random() in hashCode() to generate unique codes
C. Use the same set of significant fields in both methods
D. Exclude mutable fields from equals()

Answer: C. Use the same set of significant fields in both methods

Explanation: equals() and hashCode() should consider the same fields to maintain consistency.


Question 77

Topic: Generics - Raw Types

Why should raw types be avoided in Java generics?

A. They disable compile-time type checks, leading to potential ClassCastException at runtime
B. They make the code execute slower
C. They are not supported in Java 8 and above
D. They cause the compiler to generate too many warnings

Answer: A. They disable compile-time type checks, leading to potential ClassCastException at runtime

Explanation: Using raw types bypasses the generics type safety mechanism.


Question 78

Topic: Exception Handling - finally Block

Which of the following statements is true about the finally block?

A. It is executed only if an exception is thrown
B. It is executed whether or not an exception is thrown
C. It is not executed if the method returns before reaching it
D. It can override exceptions thrown in the try block

Answer: B. It is executed whether or not an exception is thrown

Explanation: The finally block always executes after try/catch, except when the JVM exits.


Question 79

Topic: OOP Principle - Encapsulation

Encapsulation is:

A. Hiding implementation details and exposing only the interface
B. Inheriting properties from a superclass
C. Modifying the behavior of a method in a subclass
D. Allowing multiple methods to have the same name

Answer: A. Hiding implementation details and exposing only the interface

Explanation: Encapsulation involves bundling data and methods and restricting access.


Question 80

Topic: Polymorphism in Interfaces

Given:

interface A {
    default void method() {
        System.out.println("Interface A");
    }
}
 
interface B {
    default void method() {
        System.out.println("Interface B");
    }
}
 
class C implements A, B {
    @Override
    public void method() {
        A.super.method();
    }
}

What is the output when new C().method() is called?

A. Interface A
B. Interface B
C. Compilation error due to ambiguity
D. Both Interface A and Interface B

Answer: A. Interface A

Explanation: The class C resolves the ambiguity by explicitly calling A.super.method().


Question 81

Topic: Design Patterns - Decorator

Which description best fits the Decorator pattern?

A. Allows adding new behaviors to objects dynamically by placing them inside wrapper objects
B. Provides an interface for creating families of related or dependent objects
C. Separates the construction of a complex object from its representation
D. Defines a one-to-many dependency between objects

Answer: A. Allows adding new behaviors to objects dynamically by placing them inside wrapper objects

Explanation: The Decorator pattern wraps objects to add new behavior.


Question 82

Topic: Threads - join() Method

What does the join() method do in Java threading?

A. Starts a thread
B. Merges two threads into one
C. Causes the current thread to wait until the specified thread dies
D. Stops a thread immediately

Answer: C. Causes the current thread to wait until the specified thread dies

Explanation: join() waits for the thread to finish executing.


Question 83

Topic: Atomic Operations

Which class provides atomic operations on single variables?

A. Thread
B. AtomicInteger
C. Integer
D. Collections

Answer: B. AtomicInteger

Explanation: AtomicInteger provides atomic operations for integers.


Question 84

Topic: Resource Management with try-with-resources

Which interfaces must a resource implement to be used with the try-with-resources statement?

A. Serializable
B. Closeable or AutoCloseable
C. Flushable
D. Runnable

Answer: B. Closeable or AutoCloseable

Explanation: The resource must implement AutoCloseable (superinterface of Closeable).


Question 85

Topic: Garbage Collection Roots

Which of the following is considered a Garbage Collection Root in Java?

A. Local variables in frame stacks of threads
B. Objects referenced only by weak references
C. Objects in the Survivor space
D. Unused static variables

Answer: A. Local variables in frame stacks of threads

Explanation: GC roots include local variables, static variables, and references from native code.


Question 86

Topic: JIT Compiler

What does the Just-In-Time (JIT) compiler do in Java?

A. Compiles Java code to bytecode
B. Compiles bytecode to machine code at runtime for performance
C. Compiles bytecode to Java source code
D. Optimizes the bytecode for smaller size

Answer: B. Compiles bytecode to machine code at runtime for performance

Explanation: The JIT compiler translates bytecode to native machine code during execution.


Question 87

Topic: StackOverflowError vs. OutOfMemoryError

Which of the following scenarios is likely to cause a StackOverflowError?

A. Creating a large number of objects without releasing them
B. Deep or infinite recursion
C. Filling up the heap space with data
D. Having too many threads

Answer: B. Deep or infinite recursion

Explanation: A StackOverflowError occurs when the call stack exceeds its limit, typically due to recursion.


Question 88

Topic: static Import

Which of the following statements is true about static imports?

A. They import static methods and fields, allowing them to be used without class qualification
B. They import classes from the static package
C. They make all fields and methods of a class static
D. They are the same as normal imports

Answer: A. They import static methods and fields, allowing them to be used without class qualification

Explanation: static imports allow direct access to static members.


Question 89

Topic: Fork/Join Framework

What is the primary use of the Fork/Join framework introduced in Java 7?

A. Simplify the creation of new threads
B. Efficiently execute tasks that can be broken into smaller pieces recursively
C. Provide thread-safe collections
D. Replace the need for synchronization

Answer: B. Efficiently execute tasks that can be broken into smaller pieces recursively

Explanation: The Fork/Join framework is designed for work that can be divided into smaller tasks.


Question 90

Topic: Serializable Interface

Which of the following is false about the Serializable interface?

A. It is a marker interface with no methods
B. All fields of a Serializable class must themselves be Serializable
C. You can customize serialization by implementing writeObject() and readObject()
D. Static fields are not serialized

Answer: B. All fields of a Serializable class must themselves be Serializable

Explanation: Non-serializable fields can be marked as transient to be skipped during serialization.


Question 91

Topic: Inter-thread Communication

Which methods are used for inter-thread communication in Java?

A. start() and run()
B. wait(), notify(), and notifyAll()
C. sleep() and yield()
D. suspend() and resume()

Answer: B. wait(), notify(), and notifyAll()

Explanation: These methods facilitate communication between threads about shared resources’ status.


Question 92

Topic: Callable vs. Runnable

What is the main difference between Callable and Runnable interfaces?

A. Callable can return a result and throw a checked exception; Runnable cannot
B. Runnable can return a result; Callable cannot
C. Callable is for multi-threading; Runnable is not
D. They are functionally the same

Answer: A. Callable can return a result and throw a checked exception; Runnable cannot

Explanation: Callable has a call() method that can return a result and throw exceptions.


Question 93

Topic: OOP Principle - Polymorphism

Polymorphism allows:

A. Methods to have multiple behaviors based on the object that implements them
B. Encapsulation of data
C. A class to inherit from multiple superclasses
D. Modification of methods in a superclass

Answer: A. Methods to have multiple behaviors based on the object that implements them

Explanation: Polymorphism enables one interface to be used for a general class of actions.


Question 94

Topic: Inner Classes

Which of the following statements is true about static nested classes?

A. They can access instance variables of the outer class directly
B. They require an instance of the outer class to be instantiated
C. They are associated with the outer class, not instances
D. They cannot have static members

Answer: C. They are associated with the outer class, not instances

Explanation: Static nested classes are like any other static member.


Question 95

Topic: Serialization - Backward Compatibility

How can you maintain backward compatibility when modifying a serializable class?

A. By changing the serialVersionUID
B. By adding new fields and providing default values
C. By removing existing fields
D. By changing field types

Answer: B. By adding new fields and providing default values

Explanation: Adding fields is safe if you handle default values; changing existing fields breaks compatibility.


Question 96

Topic: Java Date and Time API (Java 8+)

Which class should you use to represent a date without time in the new Date-Time API?

A. Date
B. LocalDateTime
C. LocalDate
D. Calendar

Answer: C. LocalDate

Explanation: LocalDate represents a date without time.


Question 97

Topic: Stream API - Intermediate vs. Terminal Operations

Which of the following is a terminal operation in the Stream API?

A. filter()
B. map()
C. collect()
D. peek()

Answer: C. collect()

Explanation: collect() triggers the processing of the stream; others are intermediate operations.


Question 98

Topic: StringBuilder vs. StringBuffer

Which of the following is true?

A. StringBuilder is synchronized; StringBuffer is not
B. StringBuffer is synchronized; StringBuilder is not
C. Both are immutable
D. Both are synchronized

Answer: B. StringBuffer is synchronized; StringBuilder is not

Explanation: StringBuffer is thread-safe due to synchronization; StringBuilder is faster but not thread-safe.


Question 99

Topic: Class Initialization Order

What is the correct order of initialization blocks when a class is loaded and an object is created?

A. Static blocks, instance blocks, constructor
B. Constructor, instance blocks, static blocks
C. Instance blocks, static blocks, constructor
D. Static blocks, constructor, instance blocks

Answer: A. Static blocks, instance blocks, constructor

Explanation: Static blocks execute when the class is loaded; instance blocks execute before the constructor when an object is created.


Question 100

Topic: final, finally, and finalize()

Which statement is true regarding final, finally, and finalize() in Java?

A. final is used for exception handling
B. finally is a method called by the garbage collector
C. finalize() is used to mark variables as constants
D. finally is used to place code that must execute whether or not an exception is thrown

Answer: D. finally is used to place code that must execute whether or not an exception is thrown

Explanation: final is a keyword used to define constants or prevent inheritance; finalize() is a method called by the garbage collector; finally is used in exception handling.


These additional questions (31 to 100) delve deeper into Java OOP concepts and advanced topics that are commonly explored in technical interviews at top tech companies. Be sure to thoroughly understand the explanations, as they will help reinforce your knowledge and prepare you for challenging interview scenarios. Good luck with your studies!