← Home
☕Java Developer Interview Questions — Fresher to 5 YOEJava Dev InterviewNEW
🧱

Core Java & OOP

Fundamentals every interview starts with · 25 questions

1

What are the key features of Java?

Must Know🌱 Fresher

Platform independence (compile once to bytecode, run on any JVM), automatic memory management (garbage collection), strong static typing with runtime safety (no raw pointers), built-in multithreading support, a huge standard library, and — since Java 8 — a functional programming layer (lambdas, streams) alongside the classic OOP model.

  • Simple & object-oriented — everything (except primitives) is an object.
  • Platform-independent — "write once, run anywhere" via bytecode + JVM.
  • Robust — strong compile-time checking, exception handling, no explicit pointer arithmetic.
  • Multithreaded — threads are a first-class language/runtime concept.
  • Secure — bytecode verification, classloader sandboxing, no direct memory access.
Java Basics
2

What is the difference between JDK, JRE, and JVM?

Must Know🌱 Fresher

JVM (Java Virtual Machine) is the runtime engine that executes bytecode — it's what makes Java platform-independent. JRE (Java Runtime Environment) is the JVM plus the standard class libraries needed to run Java applications. JDK (Java Development Kit) is the JRE plus development tools — compiler (javac), debugger, jar, javadoc — needed to build Java applications.

JDK  =  JRE + dev tools (javac, jdb, jar, javadoc...)
JRE  =  JVM + standard class libraries (java.lang, java.util, ...)
JVM  =  bytecode interpreter/JIT compiler + class loader + garbage collector
JVMJava Basics
3

What are the four pillars of OOP?

Must Know🌱 Fresher
  • Encapsulation — bundling data with the methods that operate on it, hiding internal state behind an API.
  • Abstraction — exposing only what a consumer needs (interface/contract), hiding implementation detail.
  • Inheritance — a class acquiring fields/behavior from a parent class, enabling reuse and "is-a" relationships.
  • Polymorphism — the same call site behaving differently depending on the runtime type (or the overload chosen at compile time).
OOP
4

What is encapsulation and why does it matter?

Must Know🌱 Fresher

Encapsulation means keeping a class's fields private and exposing controlled access through public getters/setters or behavior methods, rather than letting outside code touch internal state directly. It matters because it lets you change the internal representation later without breaking callers, and lets you enforce invariants (validation, derived state) at a single choke point instead of trusting every caller to do the right thing.

Encapsulation examplejava
public class BankAccount {
    private double balance; // hidden internal state

    public void deposit(double amount) {
        if (amount <= 0) throw new IllegalArgumentException("amount must be positive");
        balance += amount;
    }

    public double getBalance() { return balance; }
}
OOPEncapsulation
5

What types of inheritance does Java support, and why doesn’t it support multiple inheritance of classes?

Must Know🌱 Fresher

Java supports single, multilevel, and hierarchical inheritance between classes, but not multiple inheritance of classes (a class extending two classes) — that's reserved for interfaces, which a class can implement any number of.

❌ Diamond problem (why classes can't multi-extend)
      A
     / \
    B    C     B and C both override foo()
     \  /
      D        D extends B, C -- which foo() wins?
               Ambiguous -> Java disallows this entirely.
✅ Java's answer
class D extends B { }          // single class parent only
interface X, Y { }             // multiple interfaces OK
class D implements X, Y { }    // no state clash, only behavior contracts

Since Java 8, interfaces can have default methods with bodies, which reopens a milder version of this ambiguity — see the "interface default methods" question for how that specific conflict is resolved.

OOPInheritance
6

What is the difference between compile-time and runtime polymorphism?

Must Know🌱 Fresher

Compile-time polymorphism (a.k.a. static binding) is method overloading — the compiler picks which method to call based on the argument types/count at compile time. Runtime polymorphism (dynamic binding) is method overriding — the JVM picks the actual method implementation to run based on the object's real runtime type, not its declared/reference type.

Runtime polymorphism via overridingjava
Animal a = new Dog();  // reference type Animal, runtime type Dog
a.speak();              // calls Dog.speak() -- decided at runtime (vtable dispatch)
OOPPolymorphism
7

What are the rules for method overriding in Java?

Must Know📊 Mid
  • Method name and parameter list must be identical to the parent's method.
  • Return type must be the same or a covariant (narrower subtype) of the parent's return type.
  • Access modifier can only stay the same or become more visible (can't narrow from public to protected).
  • Can't throw new or broader checked exceptions than the overridden method (unchecked exceptions have no such restriction).
  • static, private, and final methods cannot be overridden (static/private aren't polymorphic; final explicitly forbids it).
OOPOverriding
8

What is the difference between an abstract class and an interface?

Must Know🌱 Fresher
Abstract classInterface
Can have state (instance fields)Only constants (public static final) — no instance state
Single inheritance — a class extends only oneA class can implement many
Can have constructorsNo constructors
Mix of abstract + concrete methods historicallySince Java 8: default/static methods with bodies too

Rule of thumb asked in interviews: use an abstract class when subclasses share common state/implementation ("is-a" with shared code); use an interface to define a capability/contract that unrelated classes can all implement ("can-do").

OOPInterface
9

What are constructors in Java? Why don’t they have a return type?

Must Know🌱 Fresher

A constructor initializes a newly created object; it has the same name as the class and no return type — not even void — because it doesn't "return" a value, it initializes the object the JVM already allocated. If you don't write one, the compiler inserts a no-arg default constructor (only if you haven't defined any constructor yourself). Constructors can be overloaded, just like methods.

OOPConstructors
10

What does the `static` keyword mean for variables, methods, and blocks?

Must Know🌱 Fresher
  • Static variable — one copy shared across all instances of the class (class-level state, not object-level).
  • Static method — belongs to the class, callable without an instance; can't use this or access instance members directly.
  • Static block — runs once, when the class is first loaded/initialized, before any instance is created — used for one-time static setup.

main(String[] args) is static so the JVM can invoke it directly on the class without needing to construct an object first.

StaticJava Basics
11

What does the `final` keyword mean for variables, methods, and classes?

Must Know🌱 Fresher
  • final variable — value can be assigned once; for object references, the reference can't be reassigned (the referenced object's internal state can still change unless it's itself immutable).
  • final method — cannot be overridden by a subclass.
  • final class — cannot be subclassed at all (e.g. String, Integer).
Java Basics
12

What is the difference between == and .equals()?

Must Know🌱 Fresher

== compares references for objects (are they the exact same object in memory?) or values for primitives. .equals() is a method that a class can override to compare logical/content equalityinstead. The default Object.equals() just delegates to ==, so a class that doesn't override it gets reference equality by default.

== vs .equals()java
String a = new String("hi");
String b = new String("hi");
a == b;        // false -- different objects
a.equals(b);   // true  -- String overrides equals() to compare content
Java BasicsObject
13

Why must you override hashCode() when you override equals()?

Must Know📊 Mid

The contract: equal objects must produce the same hash code. Hash-based collections (HashMap, HashSet) use hashCode() first to pick a bucket, then equals() only within that bucket to confirm a match. If you override equals() but leave the default hashCode() (identity hash), two "equal" objects can land in different buckets — a map lookup with a logically equal key silently returns "not found" because it never even checks equals()against the right bucket.

Broken contract examplejava
class Point {
    int x, y;
    public boolean equals(Object o) { /* compares x, y */ return true; }
    // hashCode() NOT overridden -- still identity-based
}

Set<Point> seen = new HashSet<>();
seen.add(new Point(1, 1));
seen.contains(new Point(1, 1)); // false! different hashCode -> different bucket
ObjectCollections
14

What are the access modifiers in Java and their visibility rules?

Must Know🌱 Fresher
ModifierSame classSame packageSubclass (other package)World
private✅❌❌❌
default (no modifier)✅✅❌❌
protected✅✅✅❌
public✅✅✅✅
Java Basics
15

How does the JVM make Java platform-independent?

Important🌱 Fresher

The compiler (javac) doesn't produce native machine code — it produces bytecode (.class files), a platform-neutral instruction set. Every OS/CPU combination has its own JVM build that knows how to interpret (or JIT-compile) that same bytecode into native instructions. The source is compiled once; only the JVM needs to differ per platform.

☕ Compile once, run anywhere
Foo.java --(javac)--> Foo.class (bytecode, platform-neutral)
                              |
        +---------------------+---------------------+
        v                     v                     v
   JVM (Windows)         JVM (Linux)            JVM (macOS)
        |                     |                     |
  native machine code   native machine code   native machine code

The JVM itself has three main jobs: class loading (find/link/initialize classes on demand), bytecode verification (safety checks before execution), and execution (interpret bytecode, and JIT-compile hot methods to native code).

JVMBytecode
16

What is the difference between abstraction and encapsulation?

Important🌱 Fresher

They're often confused because both "hide" something, but they hide different things at different levels:

  • Abstraction is about design — hiding what a system does behind a simpler contract (e.g., an interface like List) so the caller doesn't need to know how it's implemented.
  • Encapsulation is about implementation — hiding how a single class stores/manages its data (private fields + public methods).

A weak answer treats them as synonyms — a good answer explains abstraction operates at the interface/design level, encapsulation at the class/field level.

OOPAbstraction
17

What are the rules for method overloading in Java?

Important🌱 Fresher
  • Same method name, different parameter list (count, type, or order) — return type alone is not enough to distinguish overloads.
  • Can vary the access modifier and can vary (or repeat) the return type.
  • Can occur in the same class, or between a superclass and subclass.
  • Resolved at compile time based on the reference/argument types (static binding); this is why it's compile-time polymorphism.
OOPOverloading
18

Can static methods be overridden in Java?

Important📊 Mid

No — static methods belong to the class, not an object instance, so they aren't part of virtual dispatch. If a subclass declares a static method with the same signature, that's method hiding, not overriding: which method runs is decided by the reference type at compile time, not the object's runtime type.

Hiding vs overridingjava
class Parent { static void greet() { System.out.println("Parent"); } }
class Child extends Parent { static void greet() { System.out.println("Child"); } }

Parent p = new Child();
p.greet(); // prints "Parent" -- resolved by reference type (Parent), not the object
OOPStatic
19

What are default and static methods in interfaces (Java 8), and how are diamond conflicts resolved?

Important📊 Mid

Java 8 let interfaces declare default methods (with a body, inherited by implementers unless overridden) and static methods (utility methods callable on the interface itself) — mainly so library maintainers could add new methods to existing interfaces (e.g. List.sort) without breaking every implementer.

If a class implements two interfaces that both declare the same default method, that's a compile error ("inherits unrelated defaults") unless the class explicitly overrides the method itself:

Resolving a default-method clashjava
interface X { default String who() { return "X"; } }
interface Y { default String who() { return "Y"; } }

class Z implements X, Y {
    // Must override -- compiler can't pick for you
    public String who() {
        return X.super.who(); // explicitly choose X's version
    }
}
InterfaceJava 8
20

What is constructor chaining? How do this() and super() work?

Important📊 Mid

Constructor chaining is one constructor invoking another so shared setup logic lives in one place. this(...) calls another constructor in the same class; super(...) calls a constructor in the parent class. Whichever you use must be the first statement in the constructor, and you can only call one of them (never both) in a single constructor.

this() and super() chainingjava
class Vehicle {
    Vehicle(String type) { System.out.println("Vehicle: " + type); }
}
class Car extends Vehicle {
    Car() { this("sedan"); }               // chains to Car(String)
    Car(String model) {
        super("car");                       // must be first statement
        System.out.println("Car: " + model);
    }
}
OOPConstructors
21

What are the uses of the `this` keyword in Java?

Important🌱 Fresher
  • Refer to the current instance — disambiguate a field from a constructor/method parameter with the same name (this.name = name;).
  • Chain constructors — this(...) to call another constructor of the same class.
  • Pass the current object as an argument to another method, or return it for method chaining (fluent builders return this).
Java Basics
22

What are the uses of the `super` keyword in Java?

Important🌱 Fresher
  • Call the parent class's constructor — super(...), must be the first statement.
  • Access a parent's field or method that's been hidden/overridden in the subclass — super.fieldName, super.method().
  • Inside a default method, disambiguate which interface's default implementation to use — InterfaceName.super.method().
Java BasicsInheritance
23

What is the order of initialization when an object is created (static blocks, instance blocks, constructors, across a class hierarchy)?

Important📊 Mid

When a class is first used, the JVM loads it and runs static members (once, ever) before any object is created; when an object is then constructed, instance members run per-instance, and — for a subclass — the parent's initialization completes fully before the child's begins.

🧵 Initialization order for `new Child()` (Child extends Parent)
1. Parent static fields + static blocks   (once, on class load, top-to-bottom)
2. Child static fields + static blocks    (once, on class load, top-to-bottom)
3. Parent instance fields + instance blocks
4. Parent constructor body
5. Child instance fields + instance blocks
6. Child constructor body

Static steps (1-2) happen exactly once per JVM (class loading); steps 3-6 repeat for every new.

StaticJVM
24

What is object cloning? What is the difference between shallow copy and deep copy?

Important📊 Mid

Cloning creates a new object with the same field values as an existing one, via Object.clone() (the class must implement the Cloneable marker interface, or it throws CloneNotSupportedException).

  • Shallow copy (what Object.clone() does by default) — copies primitive fields by value, but reference fields still point to the same nested objects as the original. Mutating a nested object through the clone affects the original too.
  • Deep copy — recursively clones nested objects as well, so the clone is fully independent. Requires manually cloning each mutable field (or serialization-based / copy-constructor approaches).

In practice, most teams avoid Cloneable entirely (it's a famously awkward API) and prefer copy constructors, static factory "of"/"copyOf" methods, or builders.

ObjectCloneable
25

What is the difference between composition and inheritance? Why is "favor composition over inheritance" good advice?

Advanced⭐ Experienced

Inheritance models "is-a" by extending a class — the subclass is tightly coupled to the parent's implementation, and that coupling is fixed at compile time (a class can only extend one parent, and changes to the parent can silently break subclasses — the "fragile base class" problem). Composition models "has-a" by holding a reference to another object and delegating to it — swappable at runtime, no inheritance hierarchy to fight, and no risk of exposing/overriding a parent's internals by accident.

Composition instead of extendingjava
class Engine { void start() { /* ... */ } }

class Car {
    private final Engine engine; // "has-a" -- composition
    Car(Engine engine) { this.engine = engine; }
    void start() { engine.start(); }
}

"Favor composition over inheritance" (Effective Java) doesn't mean never use inheritance — it means reach for it only for genuine "is-a" relationships with a stable contract (e.g. implementing an interface), and default to composition for code reuse, since it keeps classes decoupled and easier to change independently.

OOPDesign