Java Questions

Software Engineer | 50 questions | 2026

Java Interview Questions and Answers

JVM, collections, HashMap, multithreading, streams, Spring Boot. Tap a question to open the model answer, most asked first.

Java interview questions for freshers 23

Q1FresherMost asked

What is the difference between JDK, JRE and JVM?

Answer

The JVM runs bytecode. The JRE is the JVM plus the standard libraries needed to run a program. The JDK is the JRE plus the tools needed to build one.

  • JVM: the virtual machine that loads classes, checks bytecode, and runs it with an interpreter and a JIT compiler. It is platform specific, which is what makes compiled Java portable.
  • JRE: JVM + core class libraries (java.lang, java.util and so on). Since Java 11 Oracle no longer ships a separate JRE, but the idea is still useful.
  • JDK: JRE + javac, jar, jlink, jshell, debuggers and profilers.

Flow: .java source -> javac -> .class bytecode -> JVM -> machine code. "Write once, run anywhere" works because only the JVM is platform specific.

What they are checking: Whether you understand the build and run pipeline, not just three acronyms

Q2FresherMost asked

Why is String immutable in Java?

Answer

A String cannot change after it is created. Java does this on purpose, for safety, caching and speed.

  • String pool: identical literals share one object, which only works if nobody can modify it.
  • Thread safety: immutable objects can be shared between threads without locking.
  • Security: strings carry class names, file paths, URLs and credentials. If they could change after validation, checks could be bypassed.
  • Hash caching: hashCode() is computed once and cached, so Strings are fast HashMap keys.
String s = "java";
s.concat(" 21");          // returns a new String, s is unchanged
System.out.println(s);    // java

Every "modification" such as concat, replace or toUpperCase returns a new object. So changing a string again and again in a loop creates a lot of garbage. This is why StringBuilder exists.

What they are checking: Whether you can explain a design decision and what it leads to

Q3FresherMost asked

What is the difference between String, StringBuilder and StringBuffer?

Answer

String is immutable, StringBuilder is mutable and not thread safe, StringBuffer is mutable and synchronized.

StringStringBuilderStringBuffer
MutableNoYesYes
Thread safeYes (immutable)NoYes (synchronized methods)
Speed for repeated editsSlowFastestSlower than StringBuilder

Use StringBuilder when building text in a loop inside one thread. Use StringBuffer only in old code that shares one buffer between threads (rare, since you can usually avoid sharing).

StringBuilder sb = new StringBuilder();
for (int i = 0; i < 5; i++) sb.append(i).append(',');
sb.setLength(sb.length() - 1);
System.out.println(sb); // 0,1,2,3,4

For a one-line concatenation the compiler already optimises +, so do not replace it with a builder.

What they are checking: Whether you choose the right tool for building strings and know the thread safety cost

Q4FresherMost asked

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

Answer

== compares references for objects (and values for primitives). equals() compares the content when the class overrides it.

String a = new String("hi");
String b = new String("hi");
System.out.println(a == b);       // false, two objects
System.out.println(a.equals(b));  // true, same characters

String c = "hi", d = "hi";
System.out.println(c == d);       // true, same pooled literal
  • The default Object.equals() behaves like ==.
  • String, wrapper classes, List, and records override equals.
  • Never compare strings with ==. Use equals, or Objects.equals(a, b) when either may be null.
  • Beware Integer caching: Integer.valueOf(127) == Integer.valueOf(127) is true but 1000 is not.

What they are checking: Whether you know reference vs value comparison and the string pool trap

Q5FresherMost asked

Explain the contract between equals() and hashCode(). What happens if you override only one?

Answer

If two objects are equal according to equals(), they must return the same hashCode(). The reverse is not required (collisions are allowed).

If you override equals without hashCode, equal objects usually get different hash codes, so hash-based collections break:

class P { String n; P(String n){this.n=n;}
  @Override public boolean equals(Object o){ return o instanceof P p && p.n.equals(n); } }

Set<P> s = new HashSet<>();
s.add(new P("a"));
System.out.println(s.contains(new P("a"))); // usually false

The lookup computes a different bucket, so the equal element is never found.

Rules for equals: reflexive, symmetric, transitive, consistent, and x.equals(null) is false. A correct pair:

@Override public int hashCode(){ return java.util.Objects.hash(n); }

Prefer records or IDE generated methods. Use only fields that do not change while the object is a map key.

What they are checking: Whether you understand why hash collections need both methods

Q6FresherMost asked

What is the difference between ArrayList and LinkedList?

Answer

ArrayList is backed by a resizable array and LinkedList by a doubly linked list. ArrayList wins for almost every real workload.

OperationArrayListLinkedList
get(i)O(1)O(n)
add at endamortised O(1)O(1)
insert/remove in middleO(n) shiftO(1) once positioned, but finding the node is O(n)
Memorycompactextra object and two pointers per element
CPU cachefriendlypoor

LinkedList also implements Deque, so it works as a queue, but ArrayDeque is usually faster. In practice use ArrayList by default. Use LinkedList only for frequent insertions through an Iterator or ListIterator at known positions.

Tip: pass an initial capacity (new ArrayList<>(10_000)) when you know the size to avoid repeated array copies.

What they are checking: Whether you reason about speed and memory, and do not repeat the myth that linked lists are faster for inserts

Q7FresherMost asked

How does HashMap work internally?

Answer

HashMap stores entries in an array of buckets. The key's hash decides the bucket, and collisions are chained.

Steps for put(key, value):

  1. Compute hashCode() of the key and spread the bits (h ^ (h >>> 16)).
  2. Bucket index = (n - 1) & hash, where n is the table size (a power of two).
  3. If the bucket is empty, store a new node. Otherwise walk the chain, comparing with equals, and replace the value if the key exists, else append.
  4. Since Java 8, a chain longer than 8 (when the table size is at least 64) turns into a red-black tree. The worst case is then O(log n).
  5. When size exceeds capacity * 0.75 (the load factor), the table doubles and entries are redistributed.

Facts to mention: default capacity 16, one null key allowed, not thread safe, iteration order not guaranteed. get is average O(1). Keys should be immutable, and a good hashCode keeps chains short.

What they are checking: The most common Java collections question: depth on hashing, collisions and resizing

Q8FresherMost asked

What is the difference between checked and unchecked exceptions?

Answer

Checked exceptions are verified by the compiler and must be caught or declared. Unchecked exceptions (subclasses of RuntimeException and Error) are not.

  • Checked: IOException, SQLException. They represent recoverable conditions outside the program's control. You must write try/catch or throws.
  • Unchecked: NullPointerException, IllegalArgumentException, IndexOutOfBoundsException. They usually signal programming bugs.
  • Error: OutOfMemoryError, StackOverflowError. Do not catch them in normal code.
void read() throws java.io.IOException {
    try (var r = java.nio.file.Files.newBufferedReader(java.nio.file.Path.of("a.txt"))) {
        System.out.println(r.readLine());
    }
}

Modern guidance: use unchecked exceptions for most business errors. Keep checked ones where the caller can really recover. Never ignore an exception silently. Keep the cause with new MyException("msg", e).

What they are checking: Whether you know the hierarchy and a sensible exception design philosophy

Q9FresherMost asked

What is the difference between final, finally and finalize?

Answer

They are unrelated: final is a modifier, finally is a block, and finalize() is a deprecated method.

  • final: a final variable cannot be reassigned. A final method cannot be overridden. A final class cannot be extended (String is final). A final reference can still point to a mutable object.
  • finally: a block after try/catch that runs whether or not an exception occurred. It is used for cleanup. It does not run if the JVM exits (System.exit) or crashes.
  • finalize(): a method the GC could call before reclaiming an object. It has been deprecated for removal since Java 18 because it is unpredictable and slow. Use try-with-resources or Cleaner instead.
try { return 1; } finally { System.out.println("cleanup"); }

The finally block above still prints before the method returns.

What they are checking: A classic wording trap: checks that you can separate the three terms

Q10FresherMost asked

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

Answer

An interface defines a contract (what), an abstract class gives partial implementation plus state (how).

Abstract classInterface
Instance fieldsYesNo (only constants)
ConstructorsYesNo
InheritanceSingleA class can implement many
MethodsAbstract and concrete, any accessAbstract, default, static, private

Since Java 8, interfaces can have default methods, so the line is less clear. But interfaces still cannot hold instance state.

Choose an interface for capabilities that unrelated classes share (Comparable, Runnable). Choose an abstract class when subclasses share fields and common code (a template-method base class). Java 17+ adds sealed interfaces to restrict which classes may implement them.

What they are checking: Whether you can choose between them using design reasons

Q11FresherMost askedFree with sign-in

What is the difference between method overloading and overriding?

Answer

Overloading is multiple methods with the same name and different parameters in one class (compile-time polymorphism). Overriding is a subclass redefining a superclass method with the same signature (runtime polymorphism).

Q12FresherMost askedFree with sign-in

What is synchronized in Java and how does it work?

Answer

synchronized gives mutual exclusion and memory visibility: only one thread at a time can run a block guarded by the same monitor lock.

Q13FresherMost askedFree with sign-in

What does the volatile keyword do? How is it different from synchronized?

Answer

volatile guarantees visibility and ordering of a single variable across threads. It does not make compound actions atomic.

Q14FresherMost askedFree with sign-in

What are lambda expressions and functional interfaces in Java?

Answer

A lambda is a short anonymous function. It can be used wherever a functional interface (an interface with exactly one abstract method) is expected.

Q15FresherMost askedFree with sign-in

What are Java Streams? Explain map, filter, reduce and collect with an example.

Answer

A Stream is a pipeline for processing a sequence of elements declaratively. It has a source, zero or more lazy intermediate operations, and one terminal operation that triggers execution.

Q16FresherMost askedFree with sign-in

How does garbage collection work in Java? What are the main collectors?

Answer

The garbage collector frees heap memory by itself. It frees objects that can no longer be reached from GC roots (thread stacks, static fields, JNI references).

Q17FresherMost askedFree with sign-in

What is Dependency Injection and Inversion of Control in Spring?

Answer

IoC means the framework creates and wires objects instead of your code calling new. Dependency Injection is how it supplies a class its collaborators.

Q18FresherMost askedFree with sign-in

Write a simple REST controller in Spring Boot and explain the annotations.

Answer
@RestController
@RequestMapping("/api/books")
public class BookController {
    private final BookService service;
    public BookController(BookService service) { this.service = service; }

    @GetMapping("/{id}")
    public ResponseEntity<Book> get(@PathVariable Long id) {
        return...
Q19FresherMost askedFree with sign-in

What are the OOP principles in Java? Explain with a short example.

Answer

The four pillars are encapsulation, inheritance, polymorphism and abstraction.

Q20FresherMost askedFree with sign-in

Is Java pass by value or pass by reference?

Answer

Java is always pass by value. For objects, the value that is copied is the reference.

Q21FresherMost askedFree with sign-in

What are the different ways to create a thread in Java?

Answer

Extend Thread, implement Runnable (or Callable), or, in modern code, submit tasks to an executor.

Q22FresherMost askedFree with sign-in

What are Java records and when should you use them?

Answer

A record (final since Java 16) is a compact immutable data carrier. The compiler generates the constructor, accessors, equals, hashCode and toString from the component list.

Q23FresherMost askedFree with sign-in

What is the difference between @RestController and @Controller, and between @RequestParam, @PathVariable and @RequestBody?

Answer

@Controller returns view names by default (for server-rendered pages). @RestController adds @ResponseBody, so return values are written to the HTTP body as JSON.

Java interview questions for experienced 19

Q24ExperiencedMost askedFree with sign-in

How do you use Spring Data JPA? Explain entities, repositories and the N+1 problem.

Answer

Annotate a class with @Entity, extend JpaRepository, and Spring generates the implementation.

Q25ExperiencedMost askedFree with sign-in

How does @Transactional work in Spring, and what are its common pitfalls?

Answer

Spring wraps the bean in a proxy. The proxy opens a transaction before the method. It commits on normal return. It rolls back on a RuntimeException or Error (not on checked exceptions by default).

Q26ExperiencedMost askedFree with sign-in

How does ConcurrentHashMap work and how is it different from HashMap and Hashtable?

Answer

ConcurrentHashMap is a thread-safe hash map. It allows concurrent reads and fine-grained writes without locking the whole map.

Q27ExperiencedMost askedFree with sign-in

Explain the Executor framework and thread pools. How do you choose a pool size?

Answer

The Executor framework separates task submission from execution. You submit tasks, and a pool of reusable threads runs them.

Q28ExperiencedMost askedFree with sign-in

What is a deadlock? How can you detect and prevent it?

Answer

A deadlock is when two or more threads each hold a lock the other needs, so none can move on.

Q29ExperiencedMost askedFree with sign-in

What does @SpringBootApplication do and how does auto-configuration work?

Answer

@SpringBootApplication combines @Configuration, @ComponentScan and @EnableAutoConfiguration.

Q30ExperiencedMost askedFree with sign-in

Explain Spring bean scopes and the bean lifecycle.

Answer

The default scope is singleton: one instance per container. Others are prototype (new instance per injection or lookup), and for web apps request, session and application.

Q31ExperiencedMost askedFree with sign-in

What is the difference between @Component, @Service, @Repository and @Controller? And @Bean vs @Component?

Answer

All four are stereotype annotations that register a class as a bean through component scanning. The last three are specialisations of @Component that add meaning.

Q32ExperiencedMost askedFree with sign-in

What is try-with-resources and how does it differ from try-finally?

Answer

Try-with-resources closes any resource that implements AutoCloseable for you. It closes in reverse order of declaration, even if an exception occurs.

Q33ExperiencedMost askedFree with sign-in

What is CompletableFuture and how do you combine async tasks?

Answer

CompletableFuture is a Future you can compose without blocking: chain steps, combine results and handle errors.

Q34ExperiencedMost askedFree with sign-in

What are virtual threads in Java 21 and when should you use them?

Answer

Virtual threads are lightweight threads scheduled by the JVM, not the OS (Project Loom, final in Java 21). Millions can exist. A blocking call such as I/O parks the virtual thread and frees its carrier platform thread.

Q35ExperiencedMost askedFree with sign-in

What is the difference between synchronized and ReentrantLock?

Answer

Both are reentrant mutual-exclusion locks. ReentrantLock adds control that synchronized lacks.

Q36ExperiencedMost askedFree with sign-in

How do you handle exceptions globally in a Spring Boot REST API?

Answer

Use @RestControllerAdvice with @ExceptionHandler methods to turn exceptions into consistent error responses, ideally RFC 7807 ProblemDetail (Spring 6).

Q37ExperiencedMost askedFree with sign-in

What is the difference between lazy and eager loading in JPA and what is a LazyInitializationException?

Answer

Lazy loading fetches an association only when it is first accessed. Eager loading fetches it immediately with the parent.

Q38ExperiencedMost askedFree with sign-in

How do you implement a thread-safe singleton in Java?

Answer

The simplest safe options are an enum singleton or the initialization-on-demand holder idiom.

Q39ExperiencedMost askedFree with sign-in

Explain the difference between map and flatMap in streams, and how groupingBy works.

Answer

map transforms each element into one element. flatMap transforms each element into a stream and flattens them into one stream.

Q40ExperiencedMost askedFree with sign-in

How do you read configuration in Spring Boot? Explain profiles and @ConfigurationProperties.

Answer

Boot loads application.properties or application.yml, then profile files such as application-prod.yml, environment variables and command-line arguments. Later sources override earlier ones, so env vars win over files.

Q41ExperiencedMost askedFree with sign-in

How do you write unit tests for a Spring Boot service? What is the difference between @SpringBootTest, @WebMvcTest and Mockito mocks?

Answer

Test the smallest slice that proves the behaviour.

Q42ExperiencedMost askedFree with sign-in

What is the difference between G1, ZGC and Parallel GC, and how would you tune GC for a latency sensitive service?

Answer

Parallel gives the most throughput but has stop-the-world pauses. G1 balances pause times and throughput. ZGC aims for very short pauses whatever the heap size.

Scenario based Java interview questions 8

Q43ExperiencedMost askedScenarioFree with sign-in

Your production Java service's memory keeps growing until it crashes with OutOfMemoryError. How do you investigate?

Answer

Capture evidence, find what is retaining memory, fix it, and add a guard.

Q44ExperiencedMost askedScenarioFree with sign-in

A Java API became slow in production under load. How do you find the bottleneck?

Answer

Measure before changing anything, and narrow down from the outside in.

Q45ExperiencedMost askedScenarioFree with sign-in

Multiple threads increment a shared counter and the final value is wrong. How do you fix it?

Answer

count++ is not atomic (read, add, write), so threads overwrite each other's updates. This is a race condition.

Q46ExperiencedMost askedScenarioFree with sign-in

A HashMap lookup suddenly returns null for a key you definitely inserted. What could be wrong?

Answer

The most likely cause is a key whose hashCode or equals changed after it was added, or a broken hashCode/equals pair.

Q47FresherMost askedScenarioFree with sign-in

You get a ConcurrentModificationException while iterating a list. Why does it happen and how do you fix it?

Answer

It happens when a collection is structurally modified during iteration by anything other than the iterator itself. The fail-fast iterator compares a modCount and throws.

Q48ExperiencedMost askedScenarioFree with sign-in

How do you cache data in a Spring Boot application, and what problems should you watch for?

Answer

Enable caching with @EnableCaching and annotate methods. Back it with Caffeine for in-process or Redis for shared caches.

Q49ExperiencedMost askedScenarioFree with sign-in

How would you design pagination and sorting for a REST endpoint that returns a large list using Spring Data?

Answer

Never return unbounded lists. Accept page, size and sort parameters, validate them, and return a page with metadata.

Q50ExperiencedMost askedScenarioFree with sign-in

Your Spring Boot app fails to start with 'No qualifying bean of type found' or 'circular dependency'. How do you resolve it?

Answer

Read the failure analysis: it names the missing bean and the injection point.

Test yourself on JavaQuick MCQs, right or wrong shown instantlyStart

More Software Engineer interview questions