Java Interview Questions for Freshers (With Answers)

Last updated (2026-11-02)

These Java interview questions for freshers cover what first technical rounds actually test: core Java, OOPs, Strings and memory, collections, exceptions, threads and modern Java features. Every answer is short enough to say out loud and precise enough to survive a follow-up question.

Answers target Java 17 and Java 21, the current long-term support releases. Where a feature arrived in a specific version, the version is named, because interviewers like to ask exactly that.

How Java interviews for freshers usually run

A typical Java round for a fresher mixes concept questions with a small amount of code. The interviewer starts broad ("what is the JVM?") and keeps asking "why" until you reach the edge of what you know.

  • Concepts: OOPs, String handling, collections and exceptions come up in almost every round.
  • Output questions: short snippets where you predict the output, often around == vs equals(), static members or exception flow.
  • Coding: a DSA problem solved in Java, so you need to be comfortable with ArrayList, HashMap and StringBuilder.
  • Project discussion: why you chose a framework or data structure in a project on your resume.

How to use these Java interview questions for freshers with answers

  1. Read the question, answer it out loud first, then compare with the answer here.
  2. Type out and run every code snippet. Predicting output is a skill you build by running code, not by reading it.
  3. For each answer, prepare one follow-up you might get (for example, after HashMap internals, expect "what happens when two keys collide?").
  4. Finish with a timed AI mock interview so you practise explaining, not just knowing.

Core Java interview questions: the basics

Start here. These questions open most Java rounds and set the tone for the rest of the interview.

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

  • JVM (Java Virtual Machine): runs Java bytecode. It loads classes, verifies bytecode, interprets it and JIT compiles hot code to native machine code, and manages memory with garbage collection.
  • JRE (Java Runtime Environment): the JVM plus the core class libraries needed to run a Java program.
  • JDK (Java Development Kit): the JRE plus development tools such as javac, jar, javadoc and jshell.

Since Java 11, Oracle no longer ships a separate JRE download; you install a JDK (or build a trimmed runtime with jlink).

2.Why is Java called platform independent?

javac compiles source code into bytecode (.class files), not into machine code for one operating system. Any platform with a JVM can run that same bytecode, which is the idea behind "write once, run anywhere".

Note the nuance: the bytecode is platform independent, but the JVM itself is platform specific.

3.What are primitive types and wrapper classes? What is autoboxing?

Java has 8 primitives: byte, short, int, long, float, double, char and boolean. Each has a wrapper class (Integer, Double and so on) so it can be used where an object is needed, such as in collections.

Autoboxing is the automatic conversion from a primitive to its wrapper (int to Integer); unboxing is the reverse. Unboxing a null wrapper throws a NullPointerException.

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

For objects, == compares references (are these the same object?). equals() compares logical content, if the class overrides it, as String and the wrapper classes do. The default Object.equals() behaves like ==.

Integer a = 127, b = 127;
Integer c = 128, d = 128;
System.out.println(a == b);      // true: cached Integer
System.out.println(c == d);      // false: two different objects
System.out.println(c.equals(d)); // true: same value

Integer.valueOf() (used by autoboxing) caches values from -128 to 127, which is why the first comparison is true. Always use equals() for wrapper and String comparisons.

5.Is Java pass by value or pass by reference?

Java is always pass by value. For objects, the value that gets copied is the reference, so a method can change the object's fields but cannot make the caller's variable point to a different object.

static void change(StringBuilder sb) {
    sb.append(" world");       // visible to the caller
    sb = new StringBuilder();  // only the local copy changes
}

6.What does the static keyword mean in Java?

A static member belongs to the class, not to any instance. Static variables have one shared copy; static methods can be called without an object and cannot use this or access instance members directly.

  • Static blocks run once, when the class is initialized.
  • A static nested class does not hold a reference to an outer instance.

More on this in the static keyword topic.

7.What does the final keyword do on a variable, method and class?

  • final variable: can be assigned only once. For a reference, the reference cannot change, but the object it points to can still be mutated.
  • final method: cannot be overridden by a subclass.
  • final class: cannot be extended (String is final).

See the final keyword topic for examples.

8.Explain public static void main(String[] args).

  • public: the JVM must be able to call it from outside the class.
  • static: the JVM calls it without creating an object of the class.
  • void: it returns nothing to the JVM (use System.exit() to return a status code).
  • String[] args: command line arguments.

You can overload main, but the JVM only uses this exact signature as the classic entry point. Interviews expect this form even though newer JDKs add simpler launch options.

Java OOPs interview questions

OOPs is the most predictable part of a Java interview. Expect definitions first, then a "show me in code" follow-up.

9.What are the four pillars of OOP? Explain them with Java examples.

  • Encapsulation: keep fields private and expose behaviour through methods, so the class controls its own state.
  • Abstraction: expose what an object does, hide how. Achieved with interfaces and abstract classes.
  • Inheritance: a class reuses and extends another with extends (an IS-A relationship).
  • Polymorphism: one interface, many forms. Compile time via overloading, runtime via overriding.

The OOP notes cover each pillar in depth.

10.What is the difference between method overloading and method overriding?

OverloadingOverriding
WhereSame class (or inherited)Subclass redefines a parent method
SignatureSame name, different parameter listSame name and parameter list
ResolvedCompile time (static binding)Runtime (dynamic dispatch)
Return typeCan differSame or a subtype (covariant)

An overriding method cannot reduce visibility and cannot throw new or broader checked exceptions. Changing only the return type is not valid overloading. Read more on method overriding and overloading.

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

  • A class can extend only one abstract class but implement many interfaces.
  • Abstract classes can have instance fields, constructors and any access modifier. Interface fields are implicitly public static final.
  • Interfaces gained default and static methods in Java 8 and private methods in Java 9, so both can now hold method bodies.

Rule of thumb: use an abstract class to share state and code among closely related classes; use an interface to define a capability that unrelated classes can implement (Comparable, Runnable).

12.Can you override a static or a private method?

No. A private method is not visible to the subclass, so a method with the same signature there is simply a new method. A static method with the same signature in a subclass hides the parent's method: which one runs depends on the reference type at compile time, not the object type at runtime.

13.Why does Java not support multiple inheritance of classes?

To avoid the diamond problem: if two parent classes define the same method, the child would have an ambiguous implementation and possibly two copies of shared state. Java allows multiple inheritance of type through interfaces instead.

If two interfaces provide the same default method, the implementing class must override it, and can call a specific one with InterfaceName.super.method().

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

this(...) calls another constructor of the same class; super(...) calls a parent constructor. Either must be the first statement in a constructor, so you cannot use both in the same one. If you write neither, the compiler inserts super().

class Student extends Person {
    Student(String name) {
        this(name, "CSE");        // chains to the other constructor
    }
    Student(String name, String branch) {
        super(name);              // runs Person(String) first
        this.branch = branch;
    }
}

15.When would you prefer composition over inheritance?

Use inheritance only for a true IS-A relationship where the subclass can stand in for the parent everywhere. Otherwise prefer composition (HAS-A): hold an instance of another class and delegate to it. Composition keeps classes loosely coupled and lets you swap behaviour at runtime.

This connects to the Liskov substitution principle in SOLID, and to composition vs aggregation vs inheritance.

Strings and memory

String questions are popular because a one-line snippet can test immutability, the String pool and equality together.

16.Why is String immutable in Java?

  • String pool: literals are shared, which is only safe if no one can change them.
  • Security: class names, file paths and URLs passed as Strings cannot be altered after validation.
  • Thread safety: immutable objects can be shared across threads without locks.
  • Hashing: the hash code can be cached, which makes Strings fast HashMap keys.

Methods like concat() or toUpperCase() return a new String; the original never changes.

17.What is the String pool? How many objects does new String("java") create?

The String pool is a table of unique String literals kept by the JVM (on the heap since Java 7). A literal like "java" is looked up in the pool and reused if present.

String a = "java";
String b = "java";
String c = new String("java");
System.out.println(a == b);          // true: same pooled object
System.out.println(a == c);          // false: c is a new heap object
System.out.println(a == c.intern()); // true: intern() returns the pooled one

new String("java") creates up to two objects: the pooled literal (if not already in the pool) and a new String object on the heap.

18.What is the difference between String, StringBuilder and StringBuffer?

StringStringBuilderStringBuffer
MutableNoYesYes
Thread safeYes (immutable)NoYes (synchronized methods)
Use whenValue does not changeBuilding strings in one threadLegacy code shared across threads

Concatenating with + inside a loop creates a new String each iteration; use StringBuilder there.

19.What is the difference between stack and heap memory in Java?

  • Stack: one per thread. Holds method call frames with local variables and references. Freed automatically when a method returns. Overflowing it (usually deep recursion) throws StackOverflowError.
  • Heap: shared by all threads. Holds objects and arrays. Cleaned by the garbage collector. Running out throws OutOfMemoryError.

20.How does garbage collection work in Java?

The garbage collector frees heap objects that are no longer reachable from GC roots (local variables on thread stacks, static fields, active threads). Most collectors are generational: new objects start in the young generation, and objects that survive several collections are promoted to the old generation.

G1 has been the default collector since Java 9. System.gc() is only a request; the JVM may ignore it.

21.What is the contract between equals() and hashCode()?

  • If a.equals(b) is true, then a.hashCode() == b.hashCode() must be true.
  • Two objects with the same hash code are not necessarily equal (collisions are allowed).
  • hashCode() must stay consistent while the fields used by equals() do not change.

If you override equals() but not hashCode(), two equal objects can land in different HashMap buckets, so map.get() and set.contains() fail. Always override both, for example with Objects.equals() and Objects.hash().

Java collections interview questions

Collections questions test whether you can pick the right data structure, which matters again in the coding round.

22.What is the difference between ArrayList and LinkedList?

ArrayListLinkedList
Backed byResizable arrayDoubly linked list
get(index)O(1)O(n)
Add at endAmortized O(1)O(1)
Insert/remove in middleO(n) (shifts elements)O(1) once at the node, O(n) to find it

In practice ArrayList is the default choice because of cache-friendly memory layout. LinkedList also implements Deque, but ArrayDeque is usually faster for queues and stacks.

23.How does HashMap work internally?

  1. put(key, value) calls key.hashCode(), spreads the bits (h ^ (h >>> 16)), and computes the bucket index as (n - 1) & hash, where n is the table size (a power of two).
  2. If the bucket is empty, a new node is stored. If not, keys are compared with equals(): a match replaces the value, otherwise the new node is added to the bucket (a collision).
  3. Since Java 8, a bucket with more than 8 nodes is converted into a red-black tree (treeification), but only when the table capacity is at least 64; below that, the map resizes instead. A tree bin shrinks back to a list at 6 nodes.
  4. When size exceeds capacity times load factor (default 16 and 0.75, so 12 entries), the table doubles and entries are redistributed.

HashMap allows one null key and many null values, is not thread safe, and does not keep insertion order (use LinkedHashMap for that).

24.What is the difference between HashMap, Hashtable and ConcurrentHashMap?

  • HashMap: not synchronized, allows one null key and null values. Use in single-threaded code.
  • Hashtable: legacy class, every method synchronized on the whole table, no null keys or values.
  • ConcurrentHashMap: thread safe with fine-grained locking (CAS plus locking per bucket since Java 8), so reads do not block. No null keys or values.

25.How does HashSet ensure there are no duplicates?

HashSet is backed by a HashMap. Each element is stored as a key with a shared dummy value, so duplicates are rejected by the same hashCode() plus equals() check. This is why elements of a HashSet must implement both methods correctly.

26.What is the difference between Comparable and Comparator?

  • Comparable (java.lang): the class defines its own natural order with compareTo(). One ordering per class.
  • Comparator (java.util): a separate object with compare(), so you can define many orderings without touching the class.
students.sort(Comparator
    .comparing(Student::getCgpa).reversed()
    .thenComparing(Student::getName));

27.What are fail-fast and fail-safe iterators?

Iterators of ArrayList and HashMap are fail-fast: if the collection is structurally modified during iteration (other than through the iterator's own remove()), they throw ConcurrentModificationException, detected with an internal modCount. This is best effort, not a guarantee.

Iterators of concurrent collections such as CopyOnWriteArrayList and ConcurrentHashMap do not throw; they work on a snapshot or a weakly consistent view. To remove while looping, use iterator.remove() or list.removeIf(...).

Exceptions, multithreading and Java 8+ features

This group separates candidates who have only read about Java from those who have written it.

28.What is the difference between checked and unchecked exceptions?

  • Checked exceptions extend Exception (but not RuntimeException). The compiler forces you to catch them or declare them with throws. Examples: IOException, SQLException.
  • Unchecked exceptions extend RuntimeException and usually signal programming bugs. Examples: NullPointerException, ArrayIndexOutOfBoundsException, IllegalArgumentException.
  • Errors (OutOfMemoryError, StackOverflowError) are also unchecked and are not meant to be caught in normal code.

29.What is the difference between final, finally and finalize?

  • final: a keyword that makes a variable, method or class unchangeable, unoverridable or unextendable.
  • finally: a block after try/catch that runs whether or not an exception is thrown (unless the JVM exits, for example via System.exit()).
  • finalize(): an Object method once called by the GC before reclaiming an object. It was deprecated in Java 9 and deprecated for removal in Java 18. Use try-with-resources or java.lang.ref.Cleaner instead.

30.What is try-with-resources?

Added in Java 7, it closes any resource that implements AutoCloseable automatically at the end of the block, even if an exception is thrown. Resources close in reverse order of declaration.

try (BufferedReader br = Files.newBufferedReader(path)) {
    return br.readLine();
} // br.close() is called automatically

31.How do you create a thread? Thread vs Runnable?

Either extend Thread and override run(), or implement Runnable (or Callable to return a value) and pass it to a Thread or an ExecutorService. Implementing Runnable is preferred because your class can still extend another class and the task is separated from the thread that runs it.

Call start(), not run(). Calling run() directly executes the code on the current thread.

32.What is the difference between synchronized and volatile?

  • volatile guarantees visibility: every read sees the latest write by any thread. It does not make compound operations atomic, so count++ on a volatile field is still a race.
  • synchronized guarantees both mutual exclusion (one thread at a time in the block) and visibility.

For a simple shared counter, AtomicInteger.incrementAndGet() is usually the cleanest answer.

33.What is a functional interface and how do lambdas use it?

A functional interface has exactly one abstract method (it may also have default and static methods). A lambda, introduced in Java 8, is a compact implementation of that single method. @FunctionalInterface makes the compiler enforce the rule.

Predicate<String> isLong = s -> s.length() > 5;
Function<String, Integer> len = String::length;
Runnable task = () -> System.out.println("running");

34.What is the Stream API?

Streams (Java 8) process collections declaratively through a pipeline: a source, zero or more intermediate operations (filter, map, sorted) that are lazy, and one terminal operation (collect, count, forEach) that triggers the work. A stream cannot be reused after its terminal operation.

List<String> names = students.stream()
    .filter(s -> s.getCgpa() >= 8.0)
    .map(Student::getName)
    .sorted()
    .toList(); // toList() needs Java 16+

35.What is Optional and when should you use it?

Optional<T> (Java 8) is a container that may or may not hold a value. It is meant as a method return type that makes "no result" explicit, so callers handle it with orElse(), orElseThrow(), map() or ifPresent() instead of risking a NullPointerException.

Avoid it for fields, method parameters and collections (return an empty collection instead), and avoid calling get() without checking.

36.What are records, var and switch expressions?

  • var (Java 10): local variable type inference. The type is still static, just inferred by the compiler. Only for local variables, not fields or parameters.
  • Switch expressions (Java 14): switch that returns a value, with arrow labels and no fall-through.
  • Records (Java 16): concise immutable data classes. The compiler generates the constructor, accessors, equals(), hashCode() and toString().
record Point(int x, int y) {}

var p = new Point(1, 2);
String quadrant = switch (Integer.signum(p.x())) {
    case 1 -> "right";
    case -1 -> "left";
    default -> "on the axis";
};

Bonus for Java 21: virtual threads and pattern matching for switch are final features, and sealed classes have been final since Java 17.

Put this guide to work

Build a one-page resume, check it against a real job description, then practice your answers out loud.

Frequently asked questions

What are the most important core Java interview questions for freshers?

Expect JDK vs JRE vs JVM, == vs equals(), String immutability and the String pool, overloading vs overriding, abstract class vs interface, HashMap internals and checked vs unchecked exceptions. These come up in most fresher rounds.

Which Java version should freshers prepare for?

Prepare on Java 17 or Java 21, the current long-term support releases. Know which features came in Java 8 (lambdas, streams, Optional) and which came later (var, records, switch expressions).

How many Java OOPs interview questions should I prepare?

Cover the four pillars, overloading vs overriding, abstract classes vs interfaces, constructors, access modifiers and composition vs inheritance. Being able to write a short example for each matters more than memorising many definitions.

Do freshers need to know multithreading for Java interviews?

You should know how to create a thread, the difference between start() and run(), and what synchronized and volatile do. Deep concurrency topics are rarely expected from freshers but are a plus.

Is Java enough for DSA in coding rounds?

Yes. Java is widely accepted for coding rounds, and its collections (ArrayList, HashMap, PriorityQueue, ArrayDeque) cover most data structures you need. Practise with fast input handling and StringBuilder for output.