Skip to content

Java & OOP

Q (basic): Explain the 4 pillars of OOP with examples.

Say this (30 sec):

  • Encapsulation: bundle data with the methods that use it, and hide internal state with private fields plus getters and setters that validate. Example: BankAccount keeps balance private, and you can only change it through deposit(), which rejects negative amounts.
  • Abstraction: show what something does and hide how. Example: List (an interface). You call add() without knowing whether it’s backed by an array or a linked list.
  • Inheritance: a class reuses and extends another (Dog extends Animal). It’s an “is-a” relationship.
  • Polymorphism: one interface, many forms. Animal a = new Dog(); a.speak(); calls Dog’s version at runtime (overriding). Overloading is the compile-time form.

Common wrong answer: Saying encapsulation and abstraction are the same thing. Encapsulation is about hiding data and protecting state. Abstraction is about hiding complexity and exposing only the essentials.

Q (mid): Abstract class vs interface?

Say this (30 sec):

Abstract class Interface
Inheritance A class can extend one A class can implement many
State Can have instance fields Only public static final constants
Constructors Yes No
Methods Abstract and concrete, any access modifier Abstract, plus default and static (Java 8+) and private (Java 9+)

Use an abstract class for closely related classes that share state or code (Shape with a color field). Use an interface for a capability that unrelated classes can have (Comparable, Runnable).

Common wrong answer: “Interfaces can’t have method bodies.” They can since Java 8, with default and static methods.

Q (basic): Overloading vs overriding?

Say this:

  • Overloading: same method name, different parameter list, in the same class. Resolved at compile time (static polymorphism). The return type alone can’t tell overloads apart.
  • Overriding: a subclass gives its own version of a parent method with the same signature. Resolved at runtime through dynamic dispatch. You can’t reduce visibility, and you can’t throw broader checked exceptions. Use @Override.

Follow-ups they ask: “Can you override static methods?” No. Static methods are hidden, not overridden, because they’re resolved by the reference type at compile time. Private and final methods can’t be overridden either.

Q (basic): Composition vs inheritance?

Say this: Inheritance is “is-a”. Composition is “has-a” (Car has an Engine). Prefer composition. It’s more flexible, avoids fragile deep hierarchies, and lets you swap behavior at runtime. Use inheritance only for a real is-a relationship.

Q (basic): What does static mean?

Say this: static members belong to the class, not to instances. One copy is shared by all objects, and you access it as ClassName.member. Static methods can’t use this or instance fields directly. A static block runs once when the class is loaded. A static nested class doesn’t need an instance of the outer class. main is static so the JVM can call it without creating an object.

Q (basic): What does final mean on a variable, method, and class?

Say this: A final variable can be assigned only once. For a reference, the reference can’t change, but the object it points to can still be modified. A final method can’t be overridden. A final class can’t be extended (e.g. String).

Follow-ups they ask: “final vs finally vs finalize?” finally is a block that always runs after try/catch, for cleanup. finalize() was a GC hook. It’s deprecated, so don’t use it. Use try-with-resources instead.

Q (basic): Access modifiers?

Say this: private: same class only. Default (no modifier): same package. protected: same package plus subclasses. public: everywhere.

Q (mid): Why is String immutable? What's the String pool?

Say this (30 sec): Once a String is created, its value can’t change. Methods like concat or toUpperCase return new Strings. Reasons:

  1. The String pool can safely share one instance between many references.
  2. Security: strings are used for file paths, URLs, and class names, and those can’t be changed after a check.
  3. Thread-safety for free.
  4. The hashCode can be cached, which makes Strings good HashMap keys.

The String pool is a special area in the heap (since Java 7) that stores string literals. String a = "hi" reuses the pooled instance. new String("hi") always makes a new heap object. intern() returns the pooled copy.

Example:

String a = "hi";
String b = "hi";
String c = new String("hi");
a == b; // true (same pooled object)
a == c; // false (different objects)
a.equals(c); // true (same content)
Q (basic): String vs StringBuilder vs StringBuffer?

Say this: String is immutable. StringBuilder is mutable and not synchronized, so it’s fast. Use it to build strings in loops. StringBuffer is mutable and synchronized (thread-safe), so it’s slower and rarely needed today. Concatenating with + in a loop creates many temporary objects, so use StringBuilder.

Q (mid): == vs equals(), and the equals/hashCode contract?

Say this (30 sec): == checks whether two references point to the same object (for primitives, it compares values). equals() checks logical equality. The default Object.equals is the same as ==, so you override it. The contract: if a.equals(b), then a.hashCode() == b.hashCode() must be true. The reverse isn’t required, because different objects can collide. If you override equals but not hashCode, two “equal” objects land in different HashMap buckets. Then map.get() and set.contains() fail, and you get duplicates in a HashSet.

Example:

@Override public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof User u)) return false;
return id == u.id && Objects.equals(email, u.email);
}
@Override public int hashCode() { return Objects.hash(id, email); }

Follow-ups they ask: “Why should HashMap keys be immutable?” If a key’s fields change after you insert it, its hashCode changes and you can’t find the entry anymore.

Q (basic): ArrayList vs LinkedList?

Say this (30 sec): ArrayList is backed by a dynamic array. get(i) is O(1). Adding at the end is amortized O(1) (it grows by about 1.5x when full). Inserting or removing in the middle is O(n) because elements shift. LinkedList is a doubly linked list. get(i) is O(n). Adding or removing at the ends is O(1). It uses more memory per element because of the node pointers. In practice ArrayList wins almost always, thanks to CPU cache locality. Use ArrayDeque for a queue or stack.

Common wrong answer: “LinkedList is faster for inserting in the middle.” You still need O(n) to walk to the position. It’s only O(1) if you already hold an iterator there.

Q (tricky): How does HashMap work internally?

Say this (30 sec):

  1. Internally it’s an array of buckets (Node[]). The default capacity is 16 and the load factor is 0.75.
  2. put(k, v): compute k.hashCode(), spread the bits (h ^ (h >>> 16)), and find the bucket index = hash & (capacity - 1). Capacity is always a power of 2.
  3. If the bucket is empty, store the node. If not (a collision), walk the bucket. If a key is equals to an existing one, replace the value. Otherwise, add a new node.
  4. When one bucket holds more than 8 nodes (and capacity is at least 64), the list becomes a red-black tree, so the worst case goes from O(n) to O(log n).
  5. When size > capacity × 0.75, it resizes to double the capacity and redistributes the entries.

Average get/put is O(1). It allows one null key and many null values. It’s not thread-safe. Use ConcurrentHashMap for that. Iteration order isn’t guaranteed. LinkedHashMap keeps insertion order.

Q (mid): HashMap vs Hashtable vs ConcurrentHashMap?

Say this: HashMap isn’t synchronized and allows a null key. Hashtable is legacy, synchronizes every method (slow), and allows no nulls. ConcurrentHashMap is thread-safe with fine-grained locking (CAS plus per-bin locks since Java 8), allows no nulls, and reads don’t block. Use it for concurrent access.

Q (basic): How does HashSet work? HashSet vs TreeSet?

Say this: HashSet uses a HashMap internally. Elements are stored as keys with a dummy value. That’s why duplicates are detected with hashCode() and equals(). It’s O(1) and unordered. TreeSet is backed by a TreeMap (a red-black tree). It keeps elements sorted (natural order or a Comparator), operations are O(log n), and it doesn’t allow null.

Q (mid): What is TreeMap? When do you use it?

Say this: TreeMap is a red-black tree. Keys stay sorted, and get, put, and remove are O(log n). Use it when you need ordered keys or range queries: firstKey(), floorKey(x), ceilingKey(x), headMap(), subMap(). It’s handy in DSA problems like interval scheduling or “nearest smaller key”.

Q (basic): Comparable vs Comparator?

Say this: Comparable defines a class’s natural order inside the class with compareTo(), e.g. String or Integer. Comparator is an external, swappable order through compare(a, b). It’s used for custom sorts like list.sort(Comparator.comparing(User::getAge).reversed()).

Q (mid): Fail-fast vs fail-safe iterators?

Say this: Fail-fast iterators (ArrayList, HashMap) throw ConcurrentModificationException if the collection is changed structurally during iteration, except through iterator.remove(). Fail-safe / weakly consistent iterators (CopyOnWriteArrayList, ConcurrentHashMap) work on a snapshot or tolerate changes, so they don’t throw.

Q (basic): Checked vs unchecked exceptions?

Say this (30 sec): Checked exceptions extend Exception but not RuntimeException. The compiler forces you to catch them or declare them with throws. They’re for recoverable outside problems, e.g. IOException or SQLException. Unchecked exceptions extend RuntimeException. They aren’t enforced and usually mean programming bugs: NullPointerException, ArrayIndexOutOfBoundsException, IllegalArgumentException. Errors (OutOfMemoryError, StackOverflowError) are serious JVM problems that you normally don’t catch.

Hierarchy: Throwable has two branches, Exception (which includes RuntimeException) and Error.

Q (mid): throw vs throws? try-with-resources?

Say this: throw actually throws an exception instance: throw new IllegalArgumentException("x"). throws in a method signature declares what it might throw. try-with-resources automatically closes anything that implements AutoCloseable, even when an exception happens.

Example:

try (BufferedReader br = new BufferedReader(new FileReader("a.txt"))) {
return br.readLine();
} catch (IOException e) {
log.error("read failed", e);
}

Follow-ups they ask: “Does finally always run?” Almost always. The exceptions are System.exit(), a JVM crash, or the thread being killed.

Q (basic): JDK vs JRE vs JVM?

Say this: JVM runs bytecode: it loads classes, verifies them, interprets them, JIT-compiles hot code, and manages memory and GC. JRE = JVM + the standard libraries, everything needed to run Java. JDK = JRE + development tools (javac, jdb, jar), everything needed to develop. The flow: .java goes through javac and becomes .class bytecode, which the JVM runs on any platform. That’s “write once, run anywhere”. Since Java 11, Oracle doesn’t ship a separate JRE. You use the JDK or a custom runtime built with jlink.

Q (mid): Stack vs heap memory in Java?

Say this: Each thread has its own stack, which holds method frames, local primitives, and references. It’s freed automatically when the method returns. Too much recursion causes StackOverflowError. The heap is shared by all threads and holds all objects and arrays. It’s managed by the GC. Running out gives OutOfMemoryError. Java is always pass-by-value. For objects, the value that gets copied is the reference.

Q (mid): How does garbage collection work (basics)?

Say this (30 sec): The GC automatically frees objects that are no longer reachable from GC roots (stack references, static fields, active threads). The heap is generational, based on the observation that most objects die young. New objects go into the Young generation (Eden plus survivor spaces), which is collected often with quick minor GCs. Objects that survive several collections are promoted to the Old generation, which is collected less often (major or full GC). G1 has been the default collector since Java 9. Low-pause collectors like ZGC and Shenandoah also exist. System.gc() is only a request.

Follow-ups they ask: “Can Java have memory leaks?” Yes, logical leaks: objects that are still referenced but never used, like a growing static collection, listeners that are never removed, or caches with no eviction.

Q (basic): How do you create a thread? Thread vs Runnable?

Say this: You can extend Thread or implement Runnable / Callable. Prefer Runnable or Callable: Java has single inheritance, and it separates the task from how it’s run. Callable returns a value and can throw checked exceptions. In real code, use an ExecutorService (a thread pool) instead of creating threads by hand.

Example:

ExecutorService pool = Executors.newFixedThreadPool(4);
Future<Integer> f = pool.submit(() -> compute());
int result = f.get();
pool.shutdown();

Common wrong answer: Calling thread.run() instead of thread.start(). run() just runs the code on the current thread.

Q (mid): What is synchronized? What is volatile?

Say this (30 sec): A race condition happens when threads read and write shared data at the same time and the result depends on timing. For example, count++ is really a read, an add, and a write. synchronized takes a lock (monitor), so only one thread runs that block at a time. It gives both mutual exclusion and visibility. volatile only guarantees visibility: reads and writes go to main memory, so other threads see the latest value. It does not make count++ atomic. Use AtomicInteger or a lock for that.

Q (mid): What is a deadlock? How do you avoid it?

Say this: Two or more threads each hold a lock and wait for a lock the other one holds, so they wait forever. Example: T1 holds A and wants B, while T2 holds B and wants A. To avoid it: always take locks in the same global order, use tryLock with a timeout, keep locked sections small, and avoid nested locks.

Q (basic): Process vs thread?

Say this: A process is an independent program with its own memory space, so it’s isolated and heavier to create. A thread is a unit of execution inside a process. Threads share the process’s heap but each has its own stack, so they’re lighter and communicate easily, but they need synchronization. (Java 21 added virtual threads: very lightweight threads managed by the JVM, good for blocking I/O at scale.)

Q (mid): Explain SOLID with short examples.

Say this (30 sec):

  • S, Single Responsibility: a class has one reason to change. Split a UserService that also sends emails and writes PDFs into UserService, EmailService, and ReportService.
  • O, Open/Closed: open for extension, closed for modification. Add a new PaymentMethod implementation (UPI, Card) instead of adding another if/else inside processPayment.
  • L, Liskov Substitution: a subclass must be usable anywhere its parent is, without breaking anything. The classic violation: Square extends Rectangle, where setting the width also changes the height and breaks callers that expect a rectangle.
  • I, Interface Segregation: many small interfaces beat one fat one. Don’t force a Robot to implement Worker.eat(). Split it into Workable and Eatable.
  • D, Dependency Inversion: depend on abstractions, not concrete classes. OrderService depends on a PaymentGateway interface, and the concrete RazorpayGateway is injected through the constructor. That also makes testing with mocks easy.

Example (DIP):

interface PaymentGateway { void charge(int amount); }
class OrderService {
private final PaymentGateway gateway;
OrderService(PaymentGateway gateway) { this.gateway = gateway; } // injected
void checkout(int amt) { gateway.charge(amt); }
}

Follow-ups they ask: “Dependency Inversion vs Dependency Injection?” Inversion is the principle (depend on abstractions). Injection is a technique that implements it (passing dependencies in from outside).