In this article
  1. Language basics
  2. Small programs and puzzles
  3. Objects and inheritance
  4. Collections
  5. Exceptions and memory
  6. Multithreading
  7. Modern Java
  8. Follow-up questions
  9. Sources

Language basics

What is the difference between == and equals() in Java?

For primitives, == compares values. For objects, == compares references: whether both variables point to the same object. The equals() method compares logical content, but only if the class overrides it; the default in Object returns true only when the two references are the same object (Java 25 documentation, Object, September 2025). So two separately created strings with the same text are equals but not ==. Compare strings and boxed numbers with equals.

Why it is asked: it separates knowing how references work from memorising a rule.

Why can Integer 127 == 127 be true while 128 == 128 is false?

Autoboxing is the automatic conversion of an int into an Integer object. The Java Language Specification (JLS) for Java Standard Edition (SE) requires that boxing the same value between -128 and 127 gives the same object, so == is true there (JLS 5.1.7, Java SE 25 edition, 2025). Integer.valueOf always caches that range and "may cache other values" outside it (Java 25 documentation, Integer, September 2025), so == on larger values is unreliable. Use equals.

Why it is asked: it is a classic trap that tests whether you know boxed numbers are objects.

Why are Java strings immutable, and what is the string pool?

A String cannot change after it is created; a method such as toUpperCase() returns a new string. Immutability makes strings safe to share between threads and safe to use as map keys, and it lets the hash code be cached. The string pool is a shared store of string literals: two identical literals refer to one object, so "a" == "a" is true, while new String("a") creates a separate object.

Why it is asked: it checks whether you can connect a design choice to its consequences.

What is the difference between String, StringBuilder and StringBuffer?

String is immutable. StringBuilder is a mutable character buffer without synchronisation, the default for building text in one thread. StringBuffer is the older synchronised version and is rarely needed. The difference shows in loops: each += on a string copies the whole string so far. In a simple model of appending one character 10,000 times, that costs 50,005,000 character copies against about 10,000 for a builder.1

Why it is asked: it tests whether you see the hidden cost of immutability.

Is Java pass-by-value or pass-by-reference?

Java is always pass-by-value. A method receives a copy of each argument. For an object, the copy is of the reference, so the method can change the object the caller sees but cannot make the caller's variable point to a different object. Reassigning a parameter inside a method therefore has no effect outside it.

Why it is asked: many candidates say objects are passed by reference, and the follow-up exposes it. Read the full explanation: Java object oriented interview questions.

What is the difference between JDK, JRE and JVM?

The Java Virtual Machine (JVM) is the program that runs compiled Java code (Java Virtual Machine Specification, Java SE 25, chapter 1, 2025). The Java Runtime Environment (JRE) was the JVM plus the standard class libraries, enough to run programs; from Java Development Kit (JDK) 11 Oracle offers only the JDK, with no separate JRE (Oracle JDK 11 release notes, 2018). The JDK adds developer tools such as the compiler javac (JDK 25 documentation, 2025), so installing a JDK is enough to compile and run.

Why it is asked: it is the most common opener in basic rounds.

Small programs and puzzles

What does this arithmetic code print?

System.out.println(Integer.MAX_VALUE + 1);
System.out.println(-7 / 2);
System.out.println(-7 % 2);
System.out.println(0.1 + 0.2);
System.out.println('a' + 1);

It prints -2147483648, -3, -1, 0.30000000000000004 and 98, a common coding interview warm-up.1 An int has 32 bits, so adding one to its largest value, 2147483647, wraps to the smallest. Integer division rounds toward zero, and the remainder takes the sign of the left operand. Binary floating point cannot store 0.1 exactly. A char plus an int is an int, and 98 is the code of b.

Why it is asked: tracing output tests the numeric rules that cause real bugs.

How do you reverse a string in Java?

String reversed = new StringBuilder("hello").reverse().toString(); // "olleh"

The builder returns "olleh" for "hello".1 Because strings are immutable, you cannot reverse one in place. If the interviewer asks for it by hand, copy the characters into an array and swap the two ends while moving inward: linear time, constant extra space beyond the array. Swapping chars by hand breaks surrogate pairs such as emoji, which StringBuilder.reverse handles. State both costs aloud.

Why it is asked: it is a warm-up that reveals whether you reason about complexity and immutability.

How do you count word frequency with a HashMap?

Map<String, Integer> counts = new HashMap<>();
for (String w : "to be or not to be".split(" ")) counts.merge(w, 1, Integer::sum);

merge stores 1 for a new word and otherwise adds 1 to the existing count. The map ends with to=2, be=2, or=1 and not=1.1 Each word costs one constant-time lookup, so n words take linear time. A HashMap does not promise any iteration order (Java 25 documentation, HashMap, September 2025); use a TreeMap for sorted output.

Why it is asked: it tests whether you reach for a map and know its idioms.

How do you find the first duplicate in an array?

Set<Integer> seen = new HashSet<>();
for (int x : new int[]{3, 1, 4, 1, 5, 9, 2, 6, 5}) if (!seen.add(x)) return x;

HashSet.add returns false when the value is already present, so the first false marks the first repeat. For this input the answer is 1.1 One pass gives linear time and linear extra space. If extra space must be constant, sort the array in place in O(n log n) time and compare neighbours. That tells you whether a duplicate exists, but not which one appeared first. State that trade-off aloud.

Why it is asked: it checks whether you trade space for time on purpose.

Knowing it is half the job. Saying it is the other half.

Interview Clozo is an AI interview copilot for real interview rounds: it hears the question and puts a strong answer on your screen, and you say it in your own words. See the features or how it works.

Start Free Trial →

Objects and inheritance

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

If two objects are equal according to equals, calling hashCode on each must give the same integer. Unequal objects need not give different ones, though distinct hash codes can improve hash-table performance (Java 25 documentation, Object, September 2025). A class that overrides equals but not hashCode breaks HashMap and HashSet. Different strings can share a hash: "Aa" and "BB" both give 2,112, and so do all 1,024 strings built from ten blocks of either.1

Why it is asked: it tests whether you know why hashing needs both methods.

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

A class extends one superclass but can implement many interfaces. An abstract class can hold instance fields, constructors and partly implemented methods. An interface defines a capability; since Java 8 it may carry default method bodies (JDK Enhancement Proposal (JEP) 126; JEP 126, 2014) but not instance state. Choose an interface for a role that unrelated classes share, and an abstract class to share state and code among related classes.

Why it is asked: it shows whether you design with roles or only with inheritance. Read the full explanation: Java object oriented interview questions.

What is the difference between overloading and overriding?

Overloading is several methods with the same name and different parameter lists, in one class or spread across a superclass and its subclass; the compiler picks one from the argument types. Overriding is a subclass redefining an inherited method with the same signature; the JVM picks the version from the real type of the object at run time, which is what makes polymorphism work. The @Override annotation makes the compiler check that you did override.

Why it is asked: it separates compile-time from run-time decisions. Read the full explanation: Java object oriented interview questions.

Collections

How does a HashMap work internally?

A HashMap keeps key-value pairs in an array of buckets. The put method uses hashCode to pick a bucket and equals to find a matching key: a match replaces the value, otherwise an entry is added. Operations take constant time if hashing disperses keys well (Java 25 documentation, HashMap, September 2025). A crowded bucket becomes a balanced tree, so worst-case lookup improves from O(n) towards O(log n) (JEP 180, 2014). The load factor is the fill level that triggers growth; at 0.75, a 16-bucket map grows on its 13th entry.1

A HashMap put uses hashCode to pick a bucket and equals to matchFlow of five stages in a HashMap put: the call arrives with a key and a value, hashCode picks the bucket, equals looks for a matching key in that bucket, and the map replaces the value or adds a new entry.put(key, value)a key and its valuehashCode()picks the bucketBucketentries sharing the indexequals()matches a key alreadythereStorereplace the value or add anentryDiagram: Interview Clozo, CC BY 4.0 ·interview.clozo.ai/blog/java-interview-questions.html
hashCode chooses the bucket and equals decides whether the key is already in it.CC BY 4.0 — source: Java interview questions on strings, equals, HashMap, threads and modern Java
Text description of the diagram
  • The put method uses the hashCode of the key to pick a bucket.
  • The put method uses equals to find a matching key already there.
  • A match replaces the value, otherwise a new entry is added.

Why it is asked: it is the most common collections question, and follow-ups probe sizing and collisions.

How do you size a HashMap to avoid resizing?

Pass an initial capacity above 1,000 ÷ 0.75 = 1,333.33, so at least 1,334.1 With a capacity above entries ÷ load factor, 1,000 entries never trigger a rehash (Java 25 documentation, HashMap, September 2025). Since Java 19, HashMap.newHashMap(1000) does this arithmetic for you (Java 25 documentation, HashMap.newHashMap). Do not set capacity far too high: iteration time grows with the number of buckets.

Why it is asked: it checks whether you know the load factor in practice.

How do HashMap, Hashtable and ConcurrentHashMap differ?

HashMap is not thread-safe and allows one null key and null values. Hashtable is a legacy class whose methods are all synchronised, so calls contend for one lock, and it rejects nulls. ConcurrentHashMap is built for shared use: reads do not block, updates lock only part of the table, and it also rejects null keys and values. Use HashMap within one thread and ConcurrentHashMap when threads share a map.

Why it is asked: it tests thread-safety trade-offs, not only names.

What is the difference between ArrayList and LinkedList?

ArrayList stores elements in a resizable array: reading by index is constant time, and inserting or removing in the middle shifts later elements. LinkedList stores nodes that point to their neighbours: reaching an index means walking from an end, but inserting at a known node moves nothing. In practice ArrayList is the default, because contiguous memory suits the processor's cache, and LinkedList rarely wins.

Why it is asked: it separates textbook complexity from practical choice.

What is the difference between Comparable and Comparator?

Comparable is implemented by the class itself: its compareTo method defines one natural order. A Comparator is a separate object whose compare method defines an order from outside, so one class can have many orders and you can sort classes you cannot edit. The interface offers helpers such as Comparator.comparing(Person::age) (Java 25 documentation, Comparator, September 2025).

Why it is asked: sorting custom objects comes up in most collections rounds.

Exceptions and memory

What is the difference between checked and unchecked exceptions?

Checked exceptions are the subclasses of Throwable other than RuntimeException, Error and their subclasses; the compiler requires code to catch them or declare them with throws. Unchecked exceptions, meaning RuntimeException, Error and their subclasses, need no declaration. Use checked exceptions for conditions a caller can recover from, such as a missing file, and unchecked ones for programming errors such as a null reference.

Why it is asked: it reveals how you design error handling.

What does try-with-resources do?

Try-with-resources declares resources in parentheses after try. Each must implement AutoCloseable, and Java closes them when the block ends, in reverse order of creation, whether it ends normally or by exception. If the body and close() both throw, the body's exception propagates and the other is attached to it as suppressed. It replaces hand-written finally blocks that leak when closing itself fails.

Why it is asked: leaked files and connections are a common production bug.

What is the difference between final, finally and finalize?

The final keyword marks a variable that cannot be reassigned, a method that cannot be overridden or a class that cannot be extended. A finally block follows try and catch and runs whether or not an exception occurs; only events such as the JVM exiting skip it. The finalize() method was called before an object was reclaimed; it is deprecated for removal (Java 25 documentation, Object, September 2025; JEP 421, 2022) because its timing is unreliable. Use try-with-resources or a Cleaner.

Why it is asked: three similar names make a quick vocabulary check.

What are the stack and the heap, and how does garbage collection work?

Each thread has a stack holding its method calls, local primitives and local references; the heap holds the objects and is shared by all threads. Garbage collection is the automatic freeing of heap objects that no running code can still reach, starting from roots such as local variables and static fields. You cannot force it: System.gc() is only a request. A Java memory leak is an object that is still reachable but no longer needed, such as an entry in a static map.

Why it is asked: senior rounds use it to move on to memory tuning and leak hunting.

Multithreading

What is the difference between start() and run() on a thread?

Calling start() asks the JVM to create a new thread, which then calls run(). Calling run() directly is an ordinary method call: the code runs on the calling thread and nothing is concurrent. A thread can be started only once; a second start() throws IllegalThreadStateException.

Why it is asked: it is the quickest check of whether you have written threaded code.

What is the difference between synchronized and volatile?

The synchronized keyword gives mutual exclusion, one thread at a time in the block, and makes its changes visible to the next thread to enter. The volatile keyword gives visibility and ordering for one variable but not atomicity, so count++ on a volatile field can lose updates: if two threads both read 0 and both write 1, the result is 1 instead of 2.1 For counters use AtomicInteger or a lock.

Why it is asked: it tests whether you understand visibility, not only locking.

What are virtual threads, and when do you use them?

A virtual thread is a lightweight thread scheduled by the JVM rather than the operating system, so many can share a small number of operating-system threads. They became a final feature in Java 21 (JEP 444, 2023). They suit programs that mostly wait on network or file input and output, such as one thread per request, and they do not make processor-bound code faster. Executors.newVirtualThreadPerTaskExecutor() creates one per task.

Why it is asked: it shows whether your Java knowledge is current.

Modern Java

What are Java streams, and are they lazy?

A stream is a sequence of elements processed by a pipeline: a source, zero or more intermediate operations such as filter and map, and one terminal operation such as collect. Intermediate operations are lazy, so nothing runs until the terminal operation is called. A stream is single-use; OpenJDK throws IllegalStateException if you reuse it. A stream stores no data and does not modify its source.

Why it is asked: it tests whether you understand streams as pipelines and not only as a shorter loop.

What is a record in Java?

A record is a class that declares its data components in its header and acts as a shallowly immutable carrier for them; the compiler generates the constructor, accessors, equals, hashCode and toString.

record Point(int x, int y) {}

Records are final and cannot extend another class, but can implement interfaces. They were finalised in Java 16 (JEP 395, 2021).

Why it is asked: it shows whether you know the language beyond Java 8.

Follow-up questions

What Java interview questions are asked for 5 and 10 years of experience?

Questions for experienced developers usually go deeper on the same topics: how HashMap resizes and handles collisions (see above), the memory model behind volatile, the concurrency utilities, garbage collection behaviour, and the trade-offs behind a design. Reported practice varies by employer, so expect design discussion as well; the coding interview guide covers the coding part and the Spring Boot questions cover the framework.

What are the Java multithreading interview questions?

Expect the ones above on start() against run(), synchronized against volatile and virtual threads, then deadlock, thread pools and the difference between concurrent and parallel. Practise explaining a lost update with the two-thread example; it shows that you can reason about interleavings.

What Java coding questions and programs do interviewers ask?

Typically short tasks on strings, arrays and collections: reverse a string, count word frequency with a map, find the first duplicate, or work out the output of a snippet, all answered above. Say your reasoning aloud, state the time and space cost, and test an edge case; the coding interview guide walks through that routine.

Are Java interview questions for automation testing different?

They add test-specific topics such as locating elements, waits and test frameworks on top of the same core language, so the entries above still apply. See Java interview questions for automation testing and the JUnit questions.

Are Java and JavaScript the same language?

No. They are separate languages with different type systems, runtimes and uses, and only the name and some syntax are shared. For the other side, read the JavaScript interview questions.

What should you study after core Java?

A framework and a testing library, then how the pieces fit together. The Spring Boot questions and the full stack developer questions are the usual next steps.

Key takeaways
  • Compare objects with equals, and keep equals and hashCode consistent.
  • A HashMap picks a bucket with hashCode, matches with equals and grows by load factor.
  • Strings are immutable; build text in loops with StringBuilder.
  • volatile gives visibility, not atomicity; synchronized gives both.
  • Know modern Java: virtual threads, streams and records.

Sources

  1. Object (Java SE 25 & JDK 25) — Oracle, 16 Sep 2025
  2. Integer (Java SE 25 & JDK 25) — Oracle, 16 Sep 2025
  3. HashMap (Java SE 25 & JDK 25) — Oracle, 16 Sep 2025
  4. Comparator (Java SE 25 & JDK 25) — Oracle, 16 Sep 2025
  5. JDK 25 Documentation — Oracle, 16 Sep 2025
  6. The Java Virtual Machine Specification, Java SE 25 Edition, Chapter 1: Introduction — Oracle, 16 Sep 2025
  7. JDK 11 Release Notes: Important Changes and Information — Oracle, 25 Sep 2018
  8. The Java Language Specification, Java SE 25 Edition, Chapter 5: Conversions and Contexts — Oracle, 16 Sep 2025
  9. JEP 180: Handle Frequent HashMap Collisions with Balanced Trees — OpenJDK, 18 Mar 2014
  10. JEP 126: Lambda Expressions & Virtual Extension Methods — OpenJDK, 18 Mar 2014
  11. JEP 395: Records — OpenJDK, 16 Mar 2021
  12. JEP 421: Deprecate Finalization for Removal — OpenJDK, 22 Mar 2022
  13. JEP 444: Virtual Threads — OpenJDK, 19 Sep 2023