| Class | Blueprint/template for objects; defines fields and methods |
| Object | Instance of a class; allocated on heap via new keyword |
| Constructor | Special method, same name as class, no return type |
| this keyword | Reference to current object; this() calls another constructor |
| static members | Belong to class, not instance; shared across all objects |
| Object class | Root of all Java classes; provides equals, hashCode, toString, clone |
| new keyword | Allocates object on heap; calls constructor; returns reference |
| Copy constructor | Constructor taking same class instance; Java has no default one |
(ClassLoader)
Executed
(Heap Allocation)
+ Constructor
→ Destroy
Java OOP - Classes & Objects Interview Questions & Answers
Q1. What is a class in Java?
A: A class is a blueprint or template that defines the structure (fields) and behavior (methods) for objects. It is a reference type. Classes can have constructors, fields (state), methods (behavior), nested types, and initializer blocks. Objects are created (instantiated) from classes using the new keyword.
Q2. What is the difference between a class and an object?
A: A class is the design-time template (no memory for state). An object is a runtime instance allocated on the heap with actual data. Multiple objects can exist from the same class, each with their own field values. A class is defined once; objects are created many times.
// Class — blueprint (no object yet)
class Car { String color; int speed; }
// Objects — instances with own state
Car c1 = new Car(); c1.color = "Red";
Car c2 = new Car(); c2.color = "Blue";
Q3. What is a constructor in Java?
A: A constructor is a special method that initializes a new object. It has the same name as the class, no return type (not even void), and is called automatically when new is used. If no constructor is defined, Java provides a default no-arg constructor. Constructors cannot be static, final, abstract, or synchronized.
Q4. What is the difference between a default constructor and a no-arg constructor?
A: The default constructor is automatically generated by the compiler ONLY if the class defines no constructors at all. A no-arg constructor is explicitly written by the developer with no parameters. If you define ANY constructor (even with params), Java no longer provides the default — you must explicitly write a no-arg constructor if needed.
Q5. What is constructor overloading?
A: Defining multiple constructors with different parameter lists in the same class. Java determines which to call based on the arguments at the call site. Enables creating objects in different ways. One common pattern: delegate from overloaded constructors to a main constructor using this(...).
class Person {
String name; int age;
Person() { this("Unknown", 0); }
Person(String name) { this(name, 0); }
Person(String name, int age) { this.name = name; this.age = age; }
}
Q6. What is the this keyword in Java?
A: this is a reference to the current object (the instance the method/constructor is running on). Uses: disambiguate field from local variable (this.name = name), invoke another constructor (this()), pass current instance as argument, and return current instance (builder pattern).
Q7. What is the super keyword in Java?
A: super refers to the parent class. Uses: super.field (access shadowed parent field), super.method() (call overridden parent method), super() in constructor (call parent constructor — MUST be first statement). Every constructor implicitly calls super() unless super() or this() is explicitly the first statement.
Q8. What is the order of initialization in Java?
A: For class loading: static variables, then static blocks (in order of appearance). For each object creation: parent constructor first, then instance variables, then instance initializer blocks, then current constructor body. This order runs top-to-bottom within each category.
class Example {
static int s = initStatic(); // 1: static var
static { System.out.println("static block"); } // 2: static block
int i = initInstance(); // 3: instance var (per object)
{ System.out.println("instance block"); } // 4: instance block
Example() { System.out.println("constructor"); }// 5: constructor
}
Q9. Can a constructor call another constructor in the same class?
A: Yes — using this(...) as the FIRST statement in a constructor body. This is called constructor chaining. It reduces code duplication by delegating initialization to a common constructor. You cannot call both this() and super() in the same constructor (only one first-statement call allowed).
Q10. What is the difference between instance methods and static methods?
| Feature | Instance Method | Static Method |
|---|---|---|
| Access | Requires object | Via class name (or object) |
| this keyword | Available | NOT available |
| Override | Can be overridden | Hiding, not overriding |
| Instance fields | Can access | Cannot access directly |
Q11. What is the difference between static variables and instance variables?
A: Static variables: one copy per class, stored in Metaspace, shared by all instances, initialized when class loads. Instance variables: one copy per object, stored on heap with the object, initialized with each object creation. Static variables are accessed via ClassName.field; instance via objectRef.field.
Q12. What is a nested class in Java?
A: A class defined inside another class. Types: (1) Static nested class — no access to outer instance. (2) Inner class — has access to outer class instance. (3) Local class — inside a method. (4) Anonymous class — inline. Inner classes create an implicit reference to the outer object (memory leak risk if held in long-lived contexts).
Q13. What is the difference between static nested class and inner class?
A: Static nested class: declared with static, no implicit reference to outer class, can be instantiated without outer instance (new Outer.StaticNested()). Inner class: non-static, implicitly holds reference to outer instance, instantiated as outer.new Inner(). Inner class can access outer's private members; static nested cannot access non-static outer members.
Q14. What is the purpose of the final keyword on a class?
A: A final class cannot be subclassed (no inheritance). This is used when: (1) security/safety (prevent modification of behavior — e.g., String, Integer, UUID), (2) performance (JIT can optimize calls without virtual dispatch), (3) immutability (record classes in Java 16+ are implicitly final).
Q15. What is an abstract class?
A: Declared with abstract; cannot be instantiated. Can have abstract methods (no body, must be overridden by concrete subclasses) and concrete methods. Used as a template for subclasses sharing common behavior. An abstract class can have constructors (called from subclass constructors via super).
Q16. What is the difference between abstract class and interface?
| Feature | Abstract Class | Interface |
|---|---|---|
| Instance fields | Yes | No (only static final) |
| Constructors | Yes | No |
| Multiple inheritance | Only one parent class | Can implement many |
| Default methods | Concrete methods | default keyword (Java 8+) |
| Use when | Shared state + behavior | Pure contract / capability |
Q17. What is method overloading?
A: Defining multiple methods in the same class with the same name but different parameter lists (number, type, or order of parameters). Return type alone is NOT sufficient for overloading. Resolved at compile time (static polymorphism). Example: void print(int), void print(String), void print(int, String).
Q18. What is method overriding?
A: A subclass redefines a method inherited from its parent with the same signature (name + parameters). Key rules: same name and parameters, same or covariant return type, same or less restrictive access modifier, cannot throw new checked exceptions not in parent. Resolved at runtime (dynamic dispatch / runtime polymorphism). Annotate with @Override for safety.
Q19. What is the difference between overloading and overriding?
| Feature | Overloading | Overriding |
|---|---|---|
| Location | Same class | Parent-child classes |
| Parameters | Must differ | Must match exactly |
| Resolved | Compile time | Runtime |
| Type | Static polymorphism | Dynamic polymorphism |
Q20. What is the difference between new and newInstance()?
A: new: compile-time; you know the class; calls constructor directly; fastest. Class.newInstance(): deprecated in Java 9; calls no-arg constructor via reflection; wraps exceptions. Constructor.newInstance(...): current approach; calls any constructor via reflection; used in frameworks like Spring, JPA.
Q21. What is object cloning in Java?
A: Cloning creates a copy of an object. Shallow clone: copies field values (reference fields still point to same objects). Deep clone: recursively copies all referenced objects. Java's Object.clone() does shallow clone; requires implementing Cloneable interface. Prefer copy constructors or serialization-based deep clone over Cloneable (which is considered broken).
Q22. What is the difference between shallow copy and deep copy?
A: Shallow copy: new object with same field values — primitive fields copied by value, reference fields copied by reference (shared objects). Deep copy: new object AND recursively new copies of all referenced objects — completely independent. Deep copy is needed when mutable objects are nested.
// Copy constructor (manual deep copy)
class Address { String city; Address(Address a) { this.city = a.city; } }
class Person {
String name; Address addr;
Person(Person p) {
this.name = p.name; // String immutable — safe to share
this.addr = new Address(p.addr); // deep copy of mutable Address
}
}
Q23. When should you override equals() and hashCode()?
A: Override both whenever objects are stored in collections (HashMap, HashSet) or compared for equality. The contract: objects that are equal (equals() returns true) MUST have the same hash code. If you override only one, collections will behave incorrectly. Java Records automatically generate correct implementations.
Q24. What is the equals() and hashCode() contract?
A: (1) Reflexive: x.equals(x) = true. (2) Symmetric: if x.equals(y) then y.equals(x). (3) Transitive: if x.equals(y) and y.equals(z) then x.equals(z). (4) Consistent: same result on repeated calls. (5) x.equals(null) = false. HashCode contract: equal objects must have equal hash codes; unequal objects SHOULD (but don't need to) have different hash codes.
Q25. What is the toString() method and why override it?
A: Object.toString() by default returns ClassName@hexHashCode (useless for debugging). Override to return a meaningful string representation of the object's state. Used in: logging, debugging, string concatenation, println. Pattern: return all significant fields. Use @Override for safety.
Q26. What is garbage collection in Java?
A: Java automatically reclaims heap memory of objects no longer reachable via any reference chain from GC roots (stack variables, static fields, JNI refs). No explicit free/delete. GC runs in background (various algorithms: G1, ZGC, Shenandoah). Set objects to null to make them GC-eligible sooner if needed — though GC handles most cases automatically.
Q27. What is the difference between stack and heap memory in Java?
A: Stack: per-thread, stores local variables and method frames, LIFO, fixed size (StackOverflowError if exceeded), very fast access. Heap: shared across threads, stores all objects (instances of classes), managed by GC, much larger (configured with -Xmx), slightly slower. Primitives in local variables → stack; Objects always → heap.
Q28. Can a constructor throw an exception?
A: Yes — constructors can throw both checked and unchecked exceptions. If a constructor throws, the object is not created (the partially constructed object becomes eligible for GC). The new expression propagates the exception. Common use: validate arguments in constructor and throw IllegalArgumentException for invalid input.
Q29. What is the purpose of a private constructor?
A: Prevents external instantiation. Used in: Singleton pattern (only one instance, accessed via static factory method), utility classes (all-static methods — e.g., Collections, Arrays), factory pattern (control instantiation logic), enum (constructors are implicitly private).
class Singleton {
private static Singleton instance;
private Singleton() {} // prevent external instantiation
public static Singleton getInstance() {
if (instance == null) instance = new Singleton();
return instance;
}
}
Q30. What is the difference between this() and super() in constructor?
A: this(): calls another constructor in THE SAME CLASS — constructor chaining. super(): calls a constructor in the PARENT CLASS — must be the first statement. Both must appear as the very first statement in a constructor. You cannot use both in the same constructor. A constructor with this() will eventually delegate to one that calls super().
Q31. What is an immutable class and how do you create one?
A: An immutable object's state cannot change after creation. Recipe: (1) Declare class final. (2) All fields private and final. (3) No setters. (4) Initialize all fields in constructor. (5) Deep-copy mutable fields in constructor and getter. Example: String, Integer, LocalDate. Java 16+ Records provide immutability by default.
public final class Money {
private final BigDecimal amount;
private final String currency;
public Money(BigDecimal amount, String currency) {
this.amount = amount; // BigDecimal is immutable — no defensive copy needed
this.currency = currency;
}
public BigDecimal getAmount() { return amount; }
public String getCurrency() { return currency; }
}
Q32. What is the difference between Object class methods equals, hashCode, toString?
A: Object provides defaults: equals() compares references (==), hashCode() uses memory address, toString() returns ClassName@hex. These must be overridden for value-based equality. IDEs and libraries like Lombok generate correct implementations. Java 16+ Records auto-generate all three based on record components.
Q33. What is the purpose of the finalize() method?
A: finalize() was called by the GC before collecting an unreachable object — intended for resource cleanup. It's deprecated since Java 9 and marked for removal because: (1) no guarantee when it runs, (2) can resurrect objects, (3) performance impact on GC. Use try-with-resources and Cleaner (Java 9+) instead.
Q34. What is the Object.getClass() method?
A: Returns the runtime Class object of the object. Useful in reflection. Never null for a non-null object. Note: obj.getClass() == SomeClass.class is an EXACT match (no inheritance). Use instanceof or SomeClass.class.isAssignableFrom(obj.getClass()) for hierarchy checks.
Q35. What is the difference between class.isInstance() and instanceof?
A: instanceof: compile-time check, left operand must be known type. clazz.isInstance(obj): runtime check, works with dynamically determined types. clazz.isInstance(null) = false. isInstance() is used in frameworks where the type is determined at runtime (reflection, generics).
Q36. What is the difference between a utility class and a regular class?
A: A utility class has only static methods (no instance state). Typically: private constructor to prevent instantiation, all methods static. Examples: Collections, Arrays, Objects, Math. Best practice in modern Java: prefer static factory methods or instances with dependency injection over utility classes for testability.
Q37. What is the Builder pattern and why use it?
A: Builder creates complex objects step-by-step via chained method calls. Benefits: readable code when many optional parameters, avoids telescoping constructors, immutable object creation, thread-safe construction. Lombok's @Builder generates builder automatically. Used widely in Spring, JPA, AWS SDK.
User user = User.builder()
.name("Raj")
.email("raj@example.com")
.role("ADMIN")
.active(true)
.build(); // validates and creates immutable User
Q38. What is the difference between initialization and assignment?
A: Initialization: first assignment to a variable at its declaration. Assignment: changing value after initialization. Java requires local variables to be initialized before use. For instance fields: initialized via constructor, instance block, or declaration initializer. For static fields: via static block or declaration initializer.
Q39. What is the difference between reference equality and structural equality?
A: Reference equality (==): same object in memory. Structural equality (equals()): same content/state. Two distinct objects can be structurally equal but not reference-equal. Collections, caches, and business logic should use structural equality (equals). Identity-sensitive operations (like object locks with synchronized) use reference equality.
Q40. Can you instantiate an interface in Java?
A: Not directly — interfaces cannot be instantiated with new InterfaceName(). But you can create anonymous class instances: Runnable r = new Runnable() { public void run() {} };. With Java 8+ lambdas, functional interfaces are instantiated via lambda: Runnable r = () -> {};. The actual object is always of a concrete (anonymous) class.
Q41. What is the difference between early binding and late binding?
A: Early binding (static dispatch): method resolved at compile time — static methods, private methods, final methods, constructors. Late binding (dynamic dispatch): method resolved at runtime based on actual object type — instance methods in inheritance hierarchy. Late binding is what enables polymorphism in Java.
Q42. What is constructor chaining?
A: Constructors calling other constructors — either in the same class via this() or in the parent via super(). The chain always terminates at Object's constructor. Benefit: DRY — common initialization logic in one constructor; other constructors delegate to it. Must be first statement.
Q43. What is the difference between == null and Objects.isNull()?
A: Functionally equivalent for null checks. Objects.isNull(obj) is method-reference friendly: list.stream().filter(Objects::isNull). obj == null is the classic, zero-overhead check. Objects.nonNull(obj) is the inverse. Prefer Objects.requireNonNull(obj, "message") in method parameters to throw NPE with message.
Q44. What is the difference between a class having no constructor and one with an explicit no-arg constructor?
A: If no constructor is declared: compiler inserts a public no-arg constructor that calls super(). If you declare any constructor: the default is NOT generated. If you declare only a parameterized constructor, and framework/code needs no-arg (e.g., JPA entities, Jackson deserialization), you MUST explicitly add one.
Q45. What is the difference between static block and instance block?
A: Static block static { ... }: runs once when class is first loaded, before any instance is created, for static field initialization or class-wide setup. Instance block { ... }: runs every time an object is created, before the constructor body, for shared instance initialization across overloaded constructors.
Q46. What is the purpose of the abstract keyword on a method?
A: An abstract method has no body (declaration only) and must be overridden by any concrete subclass. Forces subclasses to provide implementation. A class with any abstract method must be declared abstract. Abstract methods enable the Template Method Pattern — define an algorithm skeleton in abstract class, defer specific steps to subclasses.
Q47. What is the difference between overriding and hiding static methods?
A: Instance methods are overridden (runtime polymorphism — actual object type determines dispatch). Static methods are hidden — if a subclass defines a static method with the same signature, the parent's version is accessed via the parent type, child's via child type (compile-time, no polymorphism). @Override on a static method causes compile error.
class A { static void m() { System.out.println("A"); } }
class B extends A { static void m() { System.out.println("B"); } }
A ref = new B();
ref.m(); // prints "A" — static, resolved by reference type not runtime type
Q48. What is the Cloneable interface?
A: A marker interface (no methods). Implementing it allows Object.clone() to be called without CloneNotSupportedException. The default clone() does a shallow copy. Cloneable is considered a poorly designed API — the method to enable is in Object, not Cloneable. Prefer copy constructors or static factories for copying objects.
Q49. What is the difference between a POJO and a JavaBean?
A: POJO (Plain Old Java Object): any simple Java class with no specific framework constraints. JavaBean: follows conventions — public no-arg constructor, private fields with public getters/setters using naming convention (getX/setX/isX for boolean), implements Serializable. Frameworks like Spring, JPA, Jackson work best with JavaBeans.
Q50. What is the difference between identity and equality in Java collections?
A: HashMap/HashSet use equals() + hashCode() for element identity. IdentityHashMap uses == (reference equality). TreeMap/TreeSet use compareTo(). Two equal objects (by equals) are treated as the same key in HashMap. Use IdentityHashMap when you need reference-based keying (e.g., object graph traversal).
Q51. What is encapsulation and why is it important?
A: Encapsulation bundles data (fields) and behavior (methods) together in a class, hiding internal state and requiring controlled access via public methods. Benefits: prevents invalid state (validate in setters), enables refactoring without changing public API, improves testability. Violated by public fields — always use private fields with accessors.
Q52. What are getter and setter methods?
A: Getters (accessor): public methods returning field value (getName(), isActive()). Setters (mutator): public methods setting field value with optional validation (setAge(int age) { if (age < 0) throw ... }). For immutable objects, only getters. Java 14+ records auto-generate accessor methods.
Q53. What is the difference between a reference variable being null vs pointing to an empty object?
A: Null reference: the variable holds no object reference (calling any method on it throws NullPointerException). Empty object: a valid, non-null object with default/empty field values (e.g., new ArrayList() is empty but not null). Always prefer empty object over null (null object pattern) — avoid NPE.
Q54. What is the difference between Object and object in Java?
A: Object (capital O): the java.lang.Object class — root of all Java class hierarchies. Every class implicitly extends Object. object (lowercase): not a keyword in Java (it's a keyword in C#/Kotlin for companion objects). In Java, generic code uses Object as the most general type.
Q55. What is the difference between instantiation and initialization?
A: Instantiation: creating an object in memory via new keyword — allocates heap space. Initialization: setting initial values for the object's fields — done in constructor, instance blocks, or field declarations. These happen together but are distinct steps. A partially initialized object (before constructor completes) can be visible in multi-threaded scenarios without proper synchronization.
Q56. What is the Object.wait() and notify() method?
A: wait(): releases the object's monitor and causes current thread to block until notify/notifyAll is called on the same object. notify(): wakes one waiting thread. notifyAll(): wakes all waiting threads. Must be called inside a synchronized block on the same object. Throws InterruptedException.
Q57. What is the covariant return type in method overriding?
A: An overriding method can return a subtype of the return type declared in the parent — this is covariant return type (Java 5+). Enables more specific return types without breaking the contract. Example: Object.clone() returns Object; subclass can override with specific type like Car.clone() returning Car.
Q58. What is the difference between access modifiers public, protected, default, private?
| Modifier | Same Class | Same Package | Subclass | Other Packages |
|---|---|---|---|---|
| private | ✓ | ✗ | ✗ | ✗ |
| default | ✓ | ✓ | ✗ | ✗ |
| protected | ✓ | ✓ | ✓ | ✗ |
| public | ✓ | ✓ | ✓ | ✓ |
Q59. What is the difference between an interface default method and an abstract class method?
A: Interface default method (Java 8+): provides implementation in interface, used when adding new method to interface without breaking existing implementations. Abstract class method: regular instance method with body. Key difference: default methods can be overridden but don't require being overridden; abstract class concrete methods are inherited directly.
Q60. What is the difference between compilation and runtime errors in OOP?
A: Compile-time errors: type mismatches, missing methods, access violations — caught by compiler. Runtime errors: NullPointerException (calling method on null), ClassCastException (invalid cast), StackOverflowError (infinite recursion). OOP patterns help reduce runtime errors: encapsulation validates state, factory methods enforce valid creation.
Q61. What is a Java Record (Java 16+)?
A: A record is a concise immutable data class. Automatically generates: private final fields, public canonical constructor, public accessors (field name as method), equals(), hashCode(), toString(). Records are implicitly final and extend Record. Replace most POJO/DTO classes.
record Point(int x, int y) {}
// Auto-generated: constructor, x(), y(), equals, hashCode, toString
Point p = new Point(3, 4);
System.out.println(p.x()); // 3
System.out.println(p); // Point[x=3, y=4]
Q62. What are the rules for method overriding in Java?
A: (1) Same name, parameter list. (2) Return type same or covariant subtype. (3) Access modifier same or more permissive (private → default → protected → public). (4) Cannot throw new/broader checked exceptions. (5) Cannot override static, private, final methods. (6) @Override annotation recommended. (7) Interfaces: overriding default methods allowed.
Q63. What is the difference between compile-time polymorphism and runtime polymorphism?
A: Compile-time: method overloading — compiler picks method based on declared parameter types. Runtime: method overriding — JVM picks method based on actual object type at runtime via dynamic dispatch (vtable). Example: Animal ref = new Dog(); ref.speak() calls Dog.speak(), not Animal.speak() — runtime polymorphism.
Q64. What is a sealed class (Java 17+)?
A: A sealed class/interface restricts which classes can extend/implement it using the permits clause. Permitted subclasses must be in the same package/module. Enables exhaustive pattern matching in switch (compiler knows all cases). Great for algebraic data types and domain modeling.
public sealed interface Shape permits Circle, Rectangle, Triangle {}
record Circle(double radius) implements Shape {}
record Rectangle(double width, double height) implements Shape {}
record Triangle(double base, double height) implements Shape {}
// Exhaustive switch — no default needed
double area = switch (shape) {
case Circle c -> Math.PI * c.radius() * c.radius();
case Rectangle r -> r.width() * r.height();
case Triangle t -> 0.5 * t.base() * t.height();
};
Q65. What is the difference between a class and an enum?
A: Enum: fixed set of named constants, implicitly extends java.lang.Enum, cannot extend another class, can implement interfaces, can have fields/methods/constructors (private). Class: unrestricted inheritance, unlimited instances, flexible. Enums are type-safe alternatives to int constants and enable switch expressions.
Q66. What is the difference between object creation with new vs reflection?
A: new ClassName(): compile-time safe, fast (direct bytecode), IDE support. Reflection (Constructor.newInstance()): runtime flexibility, slower (overhead of reflection API), bypasses compile-time checks. Used in frameworks (Spring IoC, JPA), test frameworks (Mockito), serialization. Always prefer new; use reflection only when class type is truly unknown at compile time.
Q67. What is the difference between an instance variable and a local variable in terms of defaults?
A: Instance variables: automatically initialized to defaults (0, false, null). Local variables: NO automatic initialization — must explicitly assign before use or compiler error. This difference trips up many candidates: field int x; prints 0; but local int x; then print(x) is a compile error.
Q68. What is the role of the Object class in Java?
A: Object is the root of the class hierarchy — every class implicitly extends Object. Provides: equals(), hashCode(), toString(), clone(), getClass(), wait(), notify(), notifyAll(), finalize(). This allows any object to be stored in Object references and all objects share the basic protocol for equality, hashing, and string representation.
Q69. What is the difference between a concrete class and an abstract class?
A: Concrete class: can be instantiated (has implementations for all inherited abstract methods). Abstract class: cannot be instantiated; may have abstract methods that subclasses must implement. Abstract classes define partial implementations as a template. Extending an abstract class with another abstract class doesn't require implementing abstract methods.
Q70. What is object-oriented design principle of "favor composition over inheritance"?
A: Composition: "has-a" — a class holds references to other classes as fields and delegates behavior. More flexible than inheritance — behavior can change at runtime, avoids tight coupling. Inheritance creates "is-a" relationships that can be brittle. Example: use a List field instead of extending ArrayList; use a Logger field instead of extending a logging class.
Q71. What is the difference between instance initializer block and constructor?
A: Instance initializer block runs before any constructor (but after super() call). Shared across all constructors — useful when multiple constructors need common initialization. Constructor runs after instance block and can receive parameters. For simple cases, initialize directly in field declarations; use instance blocks for complex initialization shared across overloaded constructors.
Q72. What is the difference between a method and a function?
A: In Java (OOP), methods belong to a class/object and have implicit access to this. Functions are standalone. Java doesn't have standalone functions — everything is a method. Java 8+ functional interfaces approximate functions. Static methods are closest to functions but still require a class context. In casual usage, "method" and "function" are often used interchangeably.
Q73. What is the difference between Object.equals() and Objects.equals()?
A: obj.equals(other): NullPointerException if obj is null. Objects.equals(a, b) (Java 7+): null-safe — returns true if both null, false if one is null, delegates to a.equals(b) otherwise. Prefer Objects.equals() in production code to avoid defensive null checks.
Q74. What is the instanceof operator and how is it used?
A: Tests if an object is an instance of a class/interface: obj instanceof ClassName. Returns false if obj is null. Java 16+ pattern matching: if (obj instanceof String s) { use s directly } — combines type check and cast. Java 21 pattern switch uses patterns in switch cases.
Q75. What are the four pillars of OOP?
A: (1) Encapsulation: hiding internal state, controlled access via methods. (2) Abstraction: exposing only essential features, hiding complexity. (3) Inheritance: reusing behavior from parent classes. (4) Polymorphism: same interface, different implementations (method overriding, interface implementation). All four work together to create maintainable, extensible systems.
Q76. What is the difference between an enum constant and a class instance?
A: Enum constants are singletons — one instance per constant, created at class load. Class instances are created with new. Enum constants can be compared with == safely (no need for equals). Class instances need equals() for value comparison. Enum constructors are implicitly private; class constructors can be public.
Q77. What is the difference between composition and aggregation?
A: Composition: strong "has-a" — child object cannot exist without parent (e.g., Heart inside Body; Heart is created and destroyed with Body). Aggregation: weak "has-a" — child can exist independently (e.g., Department has Employees; Employees exist beyond the Department). In Java, both are implemented with object references; the lifecycle management is the distinguishing factor.
Q78. What is the difference between object creation via constructor vs factory method?
A: Constructor: always creates a new object, type is fixed, naming limited to class name. Static factory method: can return cached instances, can return subtypes, descriptive names (valueOf, of, getInstance), can return null. Pattern: Integer.valueOf() caches -128..127. Best practice: consider factory methods for complex creation logic.
Q79. What is object interning?
A: Interning returns a canonical shared instance. Java interns String literals automatically. Enums are naturally interned (singletons). Integer.valueOf() interns -128..127. Custom interning: use a ConcurrentHashMap as a pool. Benefit: memory savings and == comparison instead of equals(). Risk: memory leaks if the pool grows unbounded.
Q80. What is a value object in DDD and how is it represented in Java?
A: A value object is defined by its attributes, not identity. Two value objects with the same attributes are equal. Should be immutable. Java representations: immutable class with equals/hashCode based on all fields, Java 16+ records (perfect for value objects), or enums for fixed values. Examples: Money, Address, Color, DateRange.
Q81. What happens when you compare two objects of different types with instanceof?
A: If the type in instanceof is completely unrelated to the variable's declared type (no inheritance/interface relationship), the compiler gives a compile error ("can never be an instance of"). If related, it compiles and returns true/false at runtime. null instanceof AnyType always returns false.
Q82. What is a fluent API / method chaining?
A: Methods return this (or a new object) enabling chained calls: sb.append("a").append("b").toString(). Used in builders, streams, query builders (JPA Criteria), assertj testing, Spring Security config. Makes complex configurations readable. Immutable fluent APIs (return new object each time) are thread-safe; mutable ones (return this) are not.
Q83. What is the difference between interface constant and enum?
A: Interface constants (static final fields in interface) are considered an anti-pattern ("constant interface anti-pattern"). Enums provide type-safe constants with behavior, proper namespacing, iteration (values()), switch support, and no pollution of class hierarchy. Always prefer enum over interface constants or static final int constants.
Q84. What is the difference between Object.clone() and copying via constructor?
A: Object.clone(): shallow copy, requires Cloneable implementation, checked exception, final fields can't be set after super.clone(). Copy constructor: explicit, controlled deep copy, no exceptions, clear API, works with final fields. Effective Java recommends copy constructors and copy factories over Cloneable.
Q85. What is an anonymous class?
A: A class without a name, defined and instantiated inline: Comparator<String> c = new Comparator<>() { public int compare(String a, String b) { ... } };. Can implement interfaces or extend classes. Has access to effectively final local variables. Mostly replaced by lambdas in modern Java for single-abstract-method interfaces.
Q86. What is the difference between abstract method and interface default method?
A: Abstract method: no body, must be overridden by concrete subclasses. Interface default method (Java 8+): has body, provides optional override for implementing classes. Default methods were added to evolve interfaces without breaking existing implementations. Abstract methods force the implementer to provide behavior; default methods provide optional fallback.
Q87. What is the static factory method pattern?
A: A static method that returns instances of the class. Advantages over constructors: descriptive names (LocalDate.of(), Optional.empty()), can return subtypes, can cache instances, can return null. Common names: of, valueOf, from, getInstance, create, newInstance, getType. Used extensively in Java standard library.
Q88. What is the difference between mutable and immutable objects in multi-threading?
A: Immutable objects: inherently thread-safe, no synchronization needed, freely shared across threads. Mutable objects: require synchronization (synchronized, volatile, atomic classes, concurrent collections) when shared across threads. Prefer immutable objects for shared data — String, Integer, BigDecimal are all immutable and thread-safe.
Q89. What is the difference between a class variable and an instance variable in subclasses?
A: Class variables (static): NOT involved in polymorphism — always accessed based on declared reference type, not actual type. Instance variables: also not polymorphically dispatched (only methods are). Only method calls are resolved via dynamic dispatch. Field access is resolved at compile time based on declared type.
Q90. What are the Object class methods that every Java programmer should know?
A: equals(Object), hashCode(), toString(): override for value semantics. clone(): use copy constructor instead. getClass(): runtime class (avoid in equals — use instanceof). wait(), notify(), notifyAll(): low-level concurrency. finalize(): deprecated, avoid. Modern Java: prefer records which auto-implement the important ones.
Q91. What is a Singleton class and how is it implemented thread-safely?
A: Singleton ensures only one instance per JVM. Thread-safe implementations: (1) Eager: private static final Singleton INSTANCE = new Singleton();. (2) Synchronized method: slow. (3) Double-checked locking with volatile: fast for most calls. (4) Enum singleton: best — JVM-guaranteed, serialization-safe.
// Best: Enum singleton (Effective Java Item 3)
public enum Singleton {
INSTANCE;
public void doSomething() { ... }
}
// Usage: Singleton.INSTANCE.doSomething()
Q92. What is the difference between a final method and a private method in terms of inheritance?
A: Final method: visible to subclasses but cannot be overridden. Private method: not visible to subclasses at all (not inherited). If a subclass defines a method with the same signature as a private parent method, it's a NEW method (not overriding). @Override on a method that matches a private parent method causes compile error.
Q93. What is the Comparable interface and when should a class implement it?
A: Comparable<T> defines natural ordering via compareTo(). Implement when the class has a single, obvious ordering (e.g., String alphabetically, Integer numerically, LocalDate chronologically). Enables TreeSet, TreeMap, Collections.sort() without explicit comparator. compareTo() must be consistent with equals() for correct behavior in sorted collections.
Q94. What is a WeakReference and when would you use it?
A: WeakReference allows the GC to collect the referenced object when no strong references remain. Use cases: caches (object automatically evicted when memory is needed), listener/observer registrations (avoid memory leaks). WeakHashMap uses weak keys — entries removed automatically when keys are GC'd. Get the value with ref.get(); may return null after GC.
Q95. What is the difference between SoftReference, WeakReference, and PhantomReference?
A: Strong (normal): never GC'd while reachable. Soft: GC'd when JVM needs memory (good for caches). Weak: GC'd eagerly (WeakHashMap listener caches). Phantom: already finalized, in reference queue (for pre-mortem cleanup). Memory sensitivity: Strong > Soft > Weak > Phantom.
Q96. What is the difference between lazy initialization and eager initialization?
A: Eager: object created at startup/class load time (simpler, guaranteed initialization, no null checks). Lazy: object created on first use (saves memory/time if never used). Lazy requires null check + synchronization for thread safety. Spring beans: scope controls this — singleton (eager by default), lazy with @Lazy.
Q97. What is the template method pattern?
A: An abstract class defines the overall algorithm structure (template method), deferring specific steps to abstract methods that subclasses implement. The parent controls the algorithm; subclasses fill in the blanks. Example: AbstractServlet.service() calls doGet()/doPost() which subclasses override. Prevents code duplication while allowing customization.
Q98. What is the Null Object pattern?
A: Instead of returning null, return a special object that implements the same interface but does nothing (or returns default values). Eliminates null checks throughout the code. Example: an EmptyList that implements List but all methods are no-ops. Optional<T> is Java's built-in null object pattern for single values.
Q99. What is the difference between a concrete class implementing an interface vs extending an abstract class?
A: Implementing interface: class is independent (can implement multiple), must provide all method implementations (or be abstract), no inherited state. Extending abstract class: uses up the single inheritance slot, inherits state (fields) and concrete method implementations, doesn't need to implement methods already implemented. Mix: implement multiple interfaces, optionally extend one abstract class.
Q100. How do you design a thread-safe immutable class?
A: (1) Declare class final. (2) All fields private final. (3) No setters. (4) Constructor fully initializes all fields. (5) For mutable field types (arrays, lists): defensive copy in constructor AND getter. (6) Ensure methods don't return references to mutable internal state. Once properly constructed, immutable objects are inherently thread-safe — no synchronization needed.
public final class ImmutableList {
private final List<String> items;
public ImmutableList(List<String> items) {
this.items = List.copyOf(items); // defensive copy (Java 10+)
}
public List<String> getItems() {
return Collections.unmodifiableList(items); // prevent mutation
}
}
Q101. What is the difference between a class loader and a class in Java?
A: ClassLoader loads class bytecode (.class files) into the JVM and creates the Class object. Multiple ClassLoaders can load the same class name — they create different Class objects (two objects from different loaders are NOT the same class). Bootstrap ClassLoader: JDK classes. Extension/Platform ClassLoader: extension jars. Application ClassLoader: classpath. OSGi and Spring Boot use custom classloaders.
Post a Comment
Add