Skip to content
  1. Home
  2. Interview Questions
  3. Java
Popular Languages

Java Interview Questions and Answers (2026) — Freshers to Experienced

Real Java interview questions asked in 2026 — OOP and core language basics for freshers, collections, generics, streams and records for mid-level developers, and concurrency, virtual threads, the JVM, garbage collection and troubleshooting for experienced engineers. Every answer has a quick answer, a detailed explanation and working Java code.

Updated November 2026 Reviewed by Abhishek Kumar 67 min read
56Questions
15Freshers
16Intermediate
15Experienced

Key takeaways

  • Freshers: OOP pillars, JDK/JRE/JVM, == vs equals(), String immutability, overloading vs overriding and abstract class vs interface are asked in almost every round.
  • 3–5 years: HashMap internals, the equals/hashCode contract, Streams, Optional, generics (PECS), records and sealed classes.
  • Senior: the Java Memory Model, ConcurrentHashMap, thread pools, CompletableFuture, virtual threads, GC choice, memory leaks and production troubleshooting.

What is Java, and why do interviewers ask about it?

Java is one of the most widely used programming languages for enterprise backends, Android, big-data platforms and financial systems. Modern Java (17, 21 and 25 LTS) adds records, sealed classes, pattern matching and virtual threads, so interviews in 2026 test both the classic fundamentals and these newer features.

These Java interview questions cover what service and product companies actually ask: OOP and core language basics for freshers, collections, exceptions, generics and streams for mid-level developers, and concurrency, the JVM, memory, garbage collection and design trade-offs for experienced engineers — each with a clear answer and working code.

Why companies hire for Java

  • Java powers most enterprise and banking backends (Spring Boot, microservices)
  • Huge hiring demand in service companies (TCS, Infosys, Accenture) and product companies
  • Strong typing, mature tooling and a massive ecosystem
  • Modern Java (records, virtual threads) keeps it competitive for cloud-native systems

Basic Java Interview Questions for Freshers

15 questions

Start here if you are a fresher or switching to Java. These fundamentals are asked in almost every first-round and campus interview.

How interviewers ask it“Let's start with the basics — how would you explain the main features of Java?”

What are the main features of Java?

BeginnerJava
Quick answerJava is an object-oriented, statically typed, platform-independent language whose code compiles to bytecode that runs on the Java Virtual Machine (JVM) — "write once, run anywhere".

Key features interviewers expect you to list:

  • Platform independence: .java source compiles to .class bytecode, which any JVM can run
  • Object-oriented: encapsulation, inheritance, polymorphism and abstraction
  • Automatic memory management: the garbage collector frees unreachable objects
  • Strong type system and compile-time checks
  • Built-in multithreading and a rich standard library (collections, I/O, networking, concurrency)
  • Security and robustness: no pointer arithmetic, bytecode verification, checked exceptions
💡 Interview tip: Mention modern Java too — records, sealed classes, pattern matching and virtual threads — to show you are current.
BeginnerJava
Quick answerThe JVM executes bytecode; the JRE is the JVM plus the core class libraries needed to run programs; the JDK is the JRE plus development tools such as javac, jar, javadoc and jshell.
ComponentContainsUsed for
JVMClass loader, bytecode verifier, interpreter, JIT compiler, GCRunning bytecode
JREJVM + standard librariesRunning Java applications
JDKJRE + compiler and toolsDeveloping Java applications

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

How interviewers ask it“Why is Java platform-independent but the JVM is not — and how does that matter in practice?”

Why is Java platform-independent but the JVM is not?

BeginnerJava
Quick answerJava source is compiled into bytecode, an intermediate instruction set that is the same on every operating system. Each OS and CPU has its own JVM implementation that translates that bytecode into native machine code (interpreting it, then JIT-compiling hot methods). So the bytecode is portable, while the JVM itself is platform-specific.

How interviewers ask it“Let's start with the basics — how would you explain the four pillars of OOP in Java?”

What are the four pillars of OOP in Java?

BeginnerJava
  • Encapsulation: hide state behind methods (private fields with getters/setters or behaviour methods)
  • Inheritance: a class reuses and extends another with extends
  • Polymorphism: one interface, many implementations — method overriding (runtime) and overloading (compile time)
  • Abstraction: expose what an object does, not how — via abstract classes and interfaces
Java
interface Shape { double area(); }                    // abstraction

class Circle implements Shape {                       // inheritance of a contract
    private final double r;                           // encapsulation
    Circle(double r) { this.r = r; }
    public double area() { return Math.PI * r * r; }
}

Shape s = new Circle(2);                              // polymorphism
System.out.println(s.area());

How interviewers ask it“Can you compare == and equals()? Where do people usually confuse them?”

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

BeginnerJava
Quick answer== compares references for objects (whether both variables point to the same object) and values for primitives. equals() compares logical equality as defined by the class — String, Integer and most value types override it to compare content.
Java
String a = new String("java");
String b = new String("java");
System.out.println(a == b);        // false – different objects
System.out.println(a.equals(b));   // true  – same characters
Common mistakes
  • Comparing strings or boxed numbers with ==. Integer values between -128 and 127 are cached, so == appears to work for small numbers and then fails for larger ones.

How interviewers ask it“Why are Strings immutable in Java — and how does that matter in practice?”

Why are Strings immutable in Java?

BeginnerJava
Quick answerOnce a String object is created, its value can't change; operations such as concat or replace return new objects. Java made String immutable for:
  • Security: strings hold class names, file paths, URLs and credentials that must not change after validation
  • String pool: identical literals can safely share one object, saving memory
  • Thread safety: immutable objects can be shared without synchronisation
  • Hashing: a string's hash code can be cached, which makes it a fast, reliable HashMap key

Use StringBuilder when you build strings in loops.

BeginnerJava
StringStringBuilderStringBuffer
MutableNoYesYes
Thread-safeYes (immutable)NoYes (synchronised)
PerformanceCreates a new object on every changeFastestSlower due to locking
Java
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 5; i++) sb.append(i).append(',');
System.out.println(sb);   // 0,1,2,3,4,

In practice, use StringBuilder for local string building; StringBuffer is rarely needed today.

How interviewers ask it“Can you compare method overloading and method overriding? Where do people usually confuse them?”

What is the difference between method overloading and method overriding?

BeginnerJava
Quick answerOverloading means several methods in the same class share a name but have different parameter lists; the compiler picks one at compile time. Overriding means a subclass provides its own implementation of an inherited method with the same signature; the JVM picks one at runtime based on the actual object type.
Java
class Printer {
    void print(int x)    { System.out.println("int " + x); }      // overloading
    void print(String s) { System.out.println("str " + s); }
}
class Animal { String sound() { return "..."; } }
class Dog extends Animal {
    @Override String sound() { return "Woof"; }                    // overriding
}

Rules for overriding: the same signature, a covariant return type is allowed, access can't be narrower, and it can't throw broader checked exceptions. static, private and final methods can't be overridden.

How interviewers ask it“Can you compare an abstract class and an interface? Where do people usually confuse them?”

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

BeginnerJava
Abstract classInterface
Instance fields / stateYesNo (only static final constants)
ConstructorsYesNo
MethodsAbstract and concreteAbstract, default, static and private (Java 9+)
InheritanceOne class onlyA class can implement many
Use whenRelated classes share code and stateUnrelated classes share a capability or contract

Modern guidance: depend on interfaces, and use abstract classes for a shared base implementation.

BeginnerJava
Quick answerstatic members belong to the class, not to an instance. A static field has one copy shared by all objects; a static method can be called without an object and can't use this or instance fields directly; a static block runs once when the class is loaded; a static nested class doesn't hold a reference to an outer instance.
Java
class Counter {
    static int created = 0;          // shared by all instances
    Counter() { created++; }
    static int total() { return created; }
}

How interviewers ask it“In simple words, what are access modifiers? Explain it like you would to a new teammate.”

What are access modifiers in Java?

BeginnerJava
ModifierSame classSame packageSubclass (other package)Everywhere
private✓
default (no modifier)✓✓
protected✓✓✓
public✓✓✓✓

Good practice is to keep fields private and expose the smallest public API you need.

BeginnerJava
Quick answerWrapper classes (Integer, Long, Double, Boolean…) let primitives be used as objects — for example in collections, which can't hold primitives. Autoboxing converts a primitive to its wrapper automatically; unboxing does the reverse.
Java
List<Integer> nums = new ArrayList<>();
nums.add(5);              // autoboxing: int -> Integer
int x = nums.get(0);      // unboxing: Integer -> int
Integer n = null;
// int y = n;             // NullPointerException on unboxing!
Common mistakes
  • Unboxing a null wrapper throws NullPointerException, and boxing inside hot loops creates garbage. Use primitive streams (IntStream) where it matters.

How interviewers ask it“Can you compare checked and unchecked exceptions? Where do people usually confuse them?”

What is the difference between checked and unchecked exceptions?

BeginnerJava
Quick answerChecked exceptions (subclasses of Exception but not RuntimeException, such as IOException and SQLException) must be caught or declared with throws; the compiler enforces this. Unchecked exceptions (RuntimeException and its subclasses, such as NullPointerException and IllegalArgumentException) usually signal programming errors and don't have to be declared. Error (for example OutOfMemoryError) signals serious JVM problems that you normally don't catch.
BeginnerJava
  • final — a keyword for constants, non-overridable methods and non-extendable classes
  • finally — a block that always runs after try/catch, used for cleanup (prefer try-with-resources)
  • finalize() — an old Object method called by the GC before reclaiming an object; it is deprecated for removal (since Java 18) because it is unpredictable and slow. Use AutoCloseable and Cleaner instead.

Intermediate Java Interview Questions

16 questions

Questions for candidates with 1–3 years of experience — the concepts interviewers use to check that you have actually built things with Java.

IntermediateJava
Quick answerHashMap stores entries in an array of buckets. For put(key, value) it computes key.hashCode(), spreads the bits, and maps the result to a bucket index ((n - 1) & hash). Collisions in one bucket are stored as a linked list, which is converted into a red-black tree when a bucket grows past 8 entries (and the table has at least 64 buckets), turning worst-case lookups from O(n) into O(log n).

When the size exceeds capacity × load factor (default 16 × 0.75), the table resizes to double its capacity and redistributes the entries.

Java
Map<String, Integer> stock = new HashMap<>();
stock.put("apple", 10);
stock.merge("apple", 5, Integer::sum);   // 15
stock.getOrDefault("mango", 0);          // 0
Likely follow-up questions
  • Why must keys be effectively immutable? (If a key's hashCode changes after insertion, the entry ends up in the wrong bucket and can't be found.)

How interviewers ask it“Walk me through the equals() and hashCode() contract in Java. Where does it come up in real systems?”

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

IntermediateJava
Quick answerIf two objects are equal according to equals(), they must return the same hashCode(). The reverse isn't required: unequal objects may share a hash code (a collision). Break this contract and hash-based collections (HashMap, HashSet) misbehave — you can't find keys you inserted, or duplicates appear in sets.
Java
public final class Point {
    private final int x, y;
    public Point(int x, int y) { this.x = x; this.y = y; }
    @Override public boolean equals(Object o) {
        return o instanceof Point p && p.x == x && p.y == y;
    }
    @Override public int hashCode() { return Objects.hash(x, y); }
}
// Or simply: public record Point(int x, int y) {}  — generates both

How interviewers ask it“How is ArrayList different from LinkedList, and when does the difference matter in practice?”

What is the difference between ArrayList and LinkedList?

IntermediateJava
OperationArrayListLinkedList
Get by indexO(1)O(n)
Add at endAmortised O(1)O(1)
Insert/remove in middleO(n) (shifts elements)O(1) once at the node, but O(n) to find it
MemoryCompact arrayA node object per element (more memory, poor cache locality)

ArrayList is the right default in almost every case. For queue or deque behaviour, prefer ArrayDeque over LinkedList.

IntermediateJava
  • HashMap: no ordering guarantee, O(1) average operations
  • LinkedHashMap: keeps insertion order (or access order — useful for LRU caches) at O(1)
  • TreeMap: keeps keys sorted (red-black tree), O(log n), and supports range queries (headMap, ceilingKey)
Java
Map<String, Integer> lru = new LinkedHashMap<>(16, 0.75f, true) {
    protected boolean removeEldestEntry(Map.Entry<String, Integer> e) { return size() > 100; }
};

How interviewers ask it“Can you compare fail-fast and fail-safe iterators? Where do people usually confuse them?”

What is the difference between fail-fast and fail-safe iterators?

IntermediateJava
Quick answerFail-fast iterators (ArrayList, HashMap) throw ConcurrentModificationException if the collection is structurally modified during iteration, except through the iterator itself. Fail-safe (weakly consistent) iterators from concurrent collections (ConcurrentHashMap, CopyOnWriteArrayList) don't throw; they work on a snapshot or tolerate concurrent changes.
Java
List<Integer> list = new ArrayList<>(List.of(1, 2, 3, 4));
// for (Integer i : list) if (i % 2 == 0) list.remove(i);   // ConcurrentModificationException
list.removeIf(i -> i % 2 == 0);                             // correct
IntermediateJava
Quick answerGenerics give compile-time type safety and remove casts: List<String> can only hold strings. Java implements generics with type erasure — type parameters exist only at compile time and are replaced by their bounds (usually Object) in bytecode. Consequences: you can't do new T(), T.class or instanceof List<String>, and List<String> and List<Integer> are the same class at runtime.
Java
static <T extends Comparable<T>> T max(List<T> items) {
    T best = items.get(0);
    for (T t : items) if (t.compareTo(best) > 0) best = t;
    return best;
}
IntermediateJava
Quick answerPECS — Producer Extends, Consumer Super. Use? extends T when a parameter produces values you read (you can't add to it). Use? super T when it consumes values you write.

PECS — Producer Extends, Consumer Super. Use ? extends T when a parameter produces values you read (you can't add to it). Use ? super T when it consumes values you write.

Java
static double sum(List<? extends Number> nums) {         // producer: read only
    double s = 0; for (Number n : nums) s += n.doubleValue(); return s;
}
static void fill(List<? super Integer> out) {              // consumer: write Integers
    for (int i = 0; i < 3; i++) out.add(i);
}

Collections.copy(List<? super T> dest, List<? extends T> src) is the textbook example.

How interviewers ask it“How would you explain lambda expressions and functional interfaces to a junior engineer, and what do people most often get wrong?”

What are lambda expressions and functional interfaces?

IntermediateJava
Quick answerA functional interface has exactly one abstract method (Runnable, Comparator, Function<T,R>, Predicate<T>, Supplier<T>, Consumer<T>). A lambda is a concise implementation of that method; a method reference (String::length) is shorthand for a lambda that only calls a method.
Java
List<String> names = List.of("Ravi", "Asha", "Neha");
names.stream()
     .filter(n -> n.startsWith("A"))          // Predicate
     .map(String::toUpperCase)                // Function via method reference
     .forEach(System.out::println);           // Consumer

Lambdas can capture only effectively final local variables.

IntermediateJava
Quick answerStreams process data declaratively in a pipeline: source → intermediate operations → terminal operation. Intermediate operations (filter, map, sorted, distinct) are lazy and return a new stream; nothing runs until a terminal operation (collect, forEach, reduce, count, findFirst) is called. A stream can be consumed only once.
Java
record Employee(String name, String dept, double salary) {}

Map<String, Double> avgByDept = employees.stream()
    .filter(e -> e.salary() > 30_000)
    .collect(Collectors.groupingBy(Employee::dept, Collectors.averagingDouble(Employee::salary)));
Likely follow-up questions
  • When are parallel streams a bad idea? (Small datasets, blocking I/O, shared mutable state, or when the common ForkJoinPool is shared with other work.)

How interviewers ask it“Can you compare map() and flatMap()? Where do people usually confuse them?”

What is the difference between map() and flatMap() in streams?

IntermediateJava
Quick answermap transforms each element into exactly one element. flatMap transforms each element into a stream and flattens all those streams into one — use it for one-to-many mappings.
Java
List<List<String>> skills = List.of(List.of("Java", "SQL"), List.of("Kafka"));
List<String> all = skills.stream().flatMap(List::stream).toList();   // [Java, SQL, Kafka]
IntermediateJava
Quick answerOptional<T> is a container that may or may not hold a value, designed as a return type that makes "no result" explicit instead of returning null.
Java
Optional<User> user = repo.findByEmail(email);
String city = user.map(User::address)
                  .map(Address::city)
                  .orElse("Unknown");
User u = user.orElseThrow(() -> new NotFoundException(email));

Don't use Optional for fields or method parameters, don't call get() without checking, and use OptionalInt and friends for primitives.

How interviewers ask it“Explain try-with-resources in Java in detail — what should a new team member understand about it?”

What is try-with-resources?

IntermediateJava
Quick answerTry-with-resources automatically closes any resource that implements AutoCloseable when the block ends — even on exceptions — in reverse order of declaration. If both the body and close() throw, the close exception is attached as a suppressed exception rather than hiding the original.
Java
try (var reader = Files.newBufferedReader(Path.of("data.csv"));
     var conn = dataSource.getConnection()) {
    // use reader and conn
}   // both closed automatically

How interviewers ask it“Walk me through records in Java. Where do they come up in real systems?”

What are records in Java?

IntermediateJava
Quick answerRecords (Java 16+) are concise, immutable data carriers. The compiler generates the private final fields, canonical constructor, accessors, equals, hashCode and toString. They are ideal for DTOs, API responses and value objects.
Java
public record Order(String id, BigDecimal amount) {
    public Order {                                    // compact constructor for validation
        if (amount.signum() < 0) throw new IllegalArgumentException("amount < 0");
    }
}

Records can implement interfaces and have static and instance methods, but they can't extend other classes, and their fields are final.

How interviewers ask it“Explain sealed classes and pattern matching for switch in Java in detail — what should a new team member understand about them?”

What are sealed classes and pattern matching for switch?

IntermediateJava
Quick answerSealed classes/interfaces (Java 17) restrict which classes may extend them with permits, so the compiler knows every subtype. Combined with pattern matching for switch (Java 21), you get exhaustive, type-safe branching with no default needed.
Java
sealed interface Payment permits Card, Upi, Wallet {}
record Card(String last4) implements Payment {}
record Upi(String vpa) implements Payment {}
record Wallet(String provider) implements Payment {}

static String describe(Payment p) {
    return switch (p) {
        case Card c   -> "Card ending " + c.last4();
        case Upi u    -> "UPI " + u.vpa();
        case Wallet w -> "Wallet " + w.provider();
    };   // compiler error if a new Payment type isn't handled
}

How interviewers ask it“How is Comparable different from Comparator, and when does the difference matter in practice?”

What is the difference between Comparable and Comparator?

IntermediateJava
Quick answerComparable<T> defines a class's natural ordering through compareTo inside the class itself (for example String and Integer). Comparator<T> defines external, alternative orderings without changing the class, and can be composed.
Java
employees.sort(Comparator.comparing(Employee::dept)
                         .thenComparing(Employee::salary, Comparator.reverseOrder()));

How interviewers ask it“Suppose you need to create an immutable class in Java — how do you approach it, and what can go wrong?”

How do you create an immutable class in Java?

IntermediateJava
  1. Declare the class final (or use a record)
  2. Make all fields private final
  3. Provide no setters
  4. Make defensive copies of mutable inputs and outputs (lists, dates, arrays)
Java
public final class Team {
    private final String name;
    private final List<String> members;
    public Team(String name, List<String> members) {
        this.name = name;
        this.members = List.copyOf(members);       // defensive, unmodifiable copy
    }
    public List<String> members() { return members; }
}

Advanced Java Interview Questions for Experienced Developers

15 questions

Senior-level Java questions on internals, performance, design and trade-offs — typical for 3, 5 and 7+ years of experience.

AdvancedJava
  • Heap: shared by all threads and holds objects and arrays; it is managed by the garbage collector and split into young (Eden + survivor spaces) and old generations by most collectors
  • Stack: one per thread; holds stack frames with local primitives and object references, and is freed automatically when a method returns. Too much recursion causes StackOverflowError
  • Metaspace: native memory (outside the heap since Java 8) holding class metadata
  • Code cache: JIT-compiled native code
Likely follow-up questions
  • What causes OutOfMemoryError: Java heap space versus Metaspace? (Too many live objects or a leak, versus too many loaded classes — often classloader leaks on redeploy.)
AdvancedJava
Quick answerThe GC finds objects unreachable from GC roots (thread stacks, static fields, JNI references) and reclaims their memory. Most collectors are generational, because most objects die young: frequent minor GCs clean the young generation, and fewer major GCs handle the old generation.
CollectorBest for
G1 (default)Balanced throughput and pause times for most server apps
ZGC (generational since Java 21)Very low pauses (under ~1 ms) on large heaps
ShenandoahLow pause times, concurrent compaction
ParallelMaximum throughput for batch jobs
SerialSmall heaps and single-CPU containers

Tune with GC logs (-Xlog:gc*), right-size the heap (-Xmx, or -XX:MaxRAMPercentage in containers), and fix allocation hotspots before tuning flags.

AdvancedJava
Quick answerYes. A leak in Java means objects stay reachable even though they are no longer needed. Common causes: static collections that only grow, caches without eviction, listeners never removed, ThreadLocal values not cleared in thread pools, unclosed resources, and classloader leaks.

To find them: watch heap usage after full GCs (it keeps rising), take a heap dump (jcmd <pid> GC.heap_dump file.hprof, or -XX:+HeapDumpOnOutOfMemoryError), and analyse it with Eclipse MAT or VisualVM — look at the dominator tree and the paths to GC roots. Java Flight Recorder (JFR) shows allocation hotspots in production with low overhead.

AdvancedJava
Quick answerThe Java Memory Model defines when writes by one thread become visible to other threads. Without synchronisation, threads may see stale values because of CPU caches and instruction reordering.

Happens-before rules guarantee visibility: an unlock happens-before a later lock of the same monitor; a write to a volatile field happens-before every later read of it; Thread.start() and Thread.join() create ordering edges.

volatile guarantees visibility and ordering, not atomicity — count++ on a volatile is still a race.

Java
class Worker implements Runnable {
    private volatile boolean running = true;   // visible across threads
    public void stop() { running = false; }
    public void run() { while (running) doWork(); }
}
AdvancedJava
Quick answerBoth provide mutual exclusion and visibility. synchronized is simpler: block-scoped, released automatically, and well optimised by the JVM. ReentrantLock adds tryLock with timeout, interruptible locking, optional fairness and multiple Conditions — but you must unlock in finally.
Java
private final ReentrantLock lock = new ReentrantLock();

void transfer(Account to, long amount) throws InterruptedException {
    if (lock.tryLock(1, TimeUnit.SECONDS)) {
        try { /* move money */ } finally { lock.unlock(); }
    } else {
        throw new IllegalStateException("Busy, retry later");
    }
}

With virtual threads, prefer ReentrantLock around blocking calls on older JDKs: before Java 24, blocking inside synchronized pinned the virtual thread to its carrier thread.

AdvancedJava
Quick answerIn Java 8 and later, ConcurrentHashMap uses CAS (compare-and-swap) to insert into empty buckets and locks only the first node of a bucket (fine-grained synchronized) for updates. Reads are lock-free. Iterators are weakly consistent and never throw ConcurrentModificationException. It doesn't allow null keys or values (because null would be ambiguous in concurrent reads).

Use its atomic compound operations instead of check-then-act:

Java
ConcurrentHashMap<String, LongAdder> hits = new ConcurrentHashMap<>();
hits.computeIfAbsent(page, k -> new LongAdder()).increment();
AdvancedJava
Quick answerCreating a thread per task is expensive, so an ExecutorService reuses a pool of worker threads that take tasks from a queue. ThreadPoolExecutor's key settings are core size, max size, queue type and capacity, keep-alive time and the rejection policy applied when the queue is full.
Java
ExecutorService pool = new ThreadPoolExecutor(
        8, 16, 60, TimeUnit.SECONDS,
        new ArrayBlockingQueue<>(1_000),              // bounded queue = backpressure
        new ThreadPoolExecutor.CallerRunsPolicy());
Future<Report> f = pool.submit(() -> buildReport(id));
pool.shutdown();
Common mistakes
  • Executors.newFixedThreadPool and newCachedThreadPool use an unbounded queue or unbounded threads, which can cause out-of-memory errors under load. Configure bounds explicitly.

How interviewers ask it“Walk me through virtual threads (Project Loom) in Java. Where do they come up in real systems?”

What are virtual threads (Project Loom)?

AdvancedJava
Quick answerVirtual threads (final in Java 21) are lightweight threads managed by the JVM rather than the OS. Millions can run concurrently: when one blocks on I/O, the JVM unmounts it from its carrier (platform) thread so that thread can run others. You write simple blocking, thread-per-request code and get the scalability of asynchronous code.
Java
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
    List<Future<String>> results = urls.stream()
        .map(u -> executor.submit(() -> httpGet(u)))   // 10,000 blocking calls are fine
        .toList();
}

Use them for I/O-bound work (HTTP calls, database access). They don't speed up CPU-bound tasks; don't pool them; and limit access to scarce resources (such as database connections) with semaphores. Spring Boot 3.2+ enables them with spring.threads.virtual.enabled=true.

AdvancedJava
Quick answerCompletableFuture represents an asynchronous result that you can transform and combine without blocking: thenApply (map), thenCompose (flatMap), thenCombine (zip two futures), allOf/anyOf, plus exceptionally/handle for errors and orTimeout for deadlines.
Java
CompletableFuture<User> user = supplyAsync(() -> userService.get(id), ioPool);
CompletableFuture<List<Order>> orders = supplyAsync(() -> orderService.list(id), ioPool);

CompletableFuture<Profile> profile = user
    .thenCombine(orders, Profile::new)
    .orTimeout(2, TimeUnit.SECONDS)
    .exceptionally(ex -> Profile.empty());

Always pass your own executor for blocking I/O; the default common ForkJoinPool is meant for CPU work.

AdvancedJava
Quick answerA deadlock happens when threads wait on each other's locks in a cycle — T1 holds A and waits for B, while T2 holds B and waits for A. Detect it with a thread dump (jstack <pid> or jcmd <pid> Thread.print), which reports "Found one Java-level deadlock". Prevent it by acquiring locks in a consistent global order, using tryLock with timeouts, keeping critical sections small, and preferring higher-level concurrency utilities.
AdvancedJava
Quick answerThe JVM loads classes on demand through a hierarchy of class loaders: Bootstrap (core java.*), Platform and Application/System (the classpath). With parent delegation, a loader first asks its parent to load a class and only loads it itself if the parent can't. This prevents core classes from being replaced and keeps one definition per class. Loading has phases: load → link (verify, prepare, resolve) → initialise (static initialisers run).
AdvancedJava
Quick answerThe JVM starts by interpreting bytecode, profiles which methods are "hot", and then JIT-compiles them to optimised native code (tiered compilation: C1 compiles quickly, C2 optimises aggressively with inlining, escape analysis and loop unrolling). This is why Java services get faster after warm-up.

To reduce startup and warm-up time: AppCDS (class data sharing), CRaC checkpoints, GraalVM native images (ahead-of-time compilation), or warming critical paths before taking traffic.

AdvancedJava
  • Singleton: Spring beans are singletons by default (scope managed by the container, not static fields)
  • Factory / Builder: BeanFactory, Lombok @Builder, HttpClient.newBuilder()
  • Proxy: Spring AOP — @Transactional, @Cacheable and @Async work through proxies
  • Template Method: JdbcTemplate, RestTemplate
  • Strategy: pluggable implementations injected by interface (payment providers, pricing rules)
  • Observer: Spring ApplicationEvent and listeners
  • Dependency Injection: the core of Spring — constructor injection is recommended
Likely follow-up questions
  • Why doesn't @Transactional work when one method calls another method in the same class? (The call bypasses the proxy — self-invocation.)
AdvancedJava
  • S — Single responsibility: a class has one reason to change
  • O — Open/closed: open for extension, closed for modification (add a new PaymentStrategy rather than editing a switch)
  • L — Liskov substitution: subtypes must be usable wherever their base type is expected
  • I — Interface segregation: prefer small, focused interfaces
  • D — Dependency inversion: depend on abstractions, and inject implementations
Java
interface NotificationSender { void send(String to, String msg); }   // abstraction
class OrderService {
    private final NotificationSender sender;                          // DIP via constructor injection
    OrderService(NotificationSender sender) { this.sender = sender; }
    void place(Order o) { /* ... */ sender.send(o.email(), "Order placed"); }
}

How interviewers ask it“Suppose you need to troubleshoot high CPU or slow response in a Java service — how do you approach it, and what can go wrong?”

How do you troubleshoot high CPU or slow response in a Java service?

AdvancedJava
  1. Confirm with metrics (CPU, GC time, thread counts, latency percentiles)
  2. Take several thread dumps a few seconds apart (jcmd <pid> Thread.print) and look for hot or blocked threads
  3. Record JFR (jcmd <pid> JFR.start duration=60s filename=app.jfr) and open it in JDK Mission Control to see CPU hotspots, allocations, locks and I/O
  4. Check GC logs — frequent full GCs point to memory pressure
  5. Check downstream calls (database, HTTP), connection-pool exhaustion and missing timeouts

Common culprits are tight loops, regex backtracking, excessive logging, N+1 database queries, lock contention and an undersized connection pool.

Java Coding Interview Questions (Programs with Code)

10 questions

Hands-on Java programs that are asked in coding rounds and machine tests. Read the code, then try writing it yourself without looking.

How interviewers ask it“Coding-round task — reverse a string in Java without using reverse(). Explain your approach before you write the code.”

How do you reverse a string in Java without using reverse()?

CodingJava
Quick answerUse two pointers that swap characters from both ends of a char array — O(n) time, O(n) space for the array.
Java
static String reverse(String s) {
    char[] c = s.toCharArray();
    for (int i = 0, j = c.length - 1; i < j; i++, j--) {
        char t = c[i]; c[i] = c[j]; c[j] = t;
    }
    return new String(c);
}
// Built-in alternative: new StringBuilder(s).reverse().toString()
Likely follow-up questions
  • How would you handle emojis or other surrogate pairs? (Reverse by code points: s.codePoints().)

How interviewers ask it“Live coding: Check whether a string is a palindrome in Java. Talk me through your approach first.”

How do you check whether a string is a palindrome in Java?

CodingJava
Quick answerCompare characters from both ends moving inwards; ignore case and non-alphanumeric characters if the question asks for it.
Java
static boolean isPalindrome(String s) {
    int i = 0, j = s.length() - 1;
    while (i < j) {
        char a = s.charAt(i), b = s.charAt(j);
        if (!Character.isLetterOrDigit(a)) { i++; continue; }
        if (!Character.isLetterOrDigit(b)) { j--; continue; }
        if (Character.toLowerCase(a) != Character.toLowerCase(b)) return false;
        i++; j--;
    }
    return true;
}
// isPalindrome("A man, a plan, a canal: Panama") -> true

How interviewers ask it“Can you find the first non-repeated character in a string in Java? Then walk me through the edge cases you would test.”

How do you find the first non-repeated character in a string?

CodingJava
Quick answerCount frequencies in an insertion-ordered map (or an int array for ASCII), then return the first character with count 1 — O(n).
Java
static Optional<Character> firstUnique(String s) {
    Map<Character, Integer> freq = new LinkedHashMap<>();
    for (char c : s.toCharArray()) freq.merge(c, 1, Integer::sum);
    return freq.entrySet().stream()
               .filter(e -> e.getValue() == 1)
               .map(Map.Entry::getKey)
               .findFirst();
}
// firstUnique("swiss") -> Optional[w]

How interviewers ask it“Live coding: Count word frequency using Java Streams. Talk me through your approach first.”

How do you count word frequency using Java Streams?

CodingJava
Quick answerSplit the text into words, normalise them, and group with Collectors.groupingBy and counting().
Java
Map<String, Long> freq = Arrays.stream(text.toLowerCase().split("\\W+"))
        .filter(w -> !w.isBlank())
        .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

// Top 3 words
freq.entrySet().stream()
    .sorted(Map.Entry.<String, Long>comparingByValue().reversed())
    .limit(3)
    .forEach(e -> System.out.println(e.getKey() + "=" + e.getValue()));

How interviewers ask it“Coding-round task — find the second highest number in an array in Java. Explain your approach before you write the code.”

How do you find the second highest number in an array?

CodingJava
Quick answerTrack the largest and second-largest distinct values in one pass — O(n) time, O(1) space.
Java
static OptionalInt secondHighest(int[] a) {
    Integer first = null, second = null;
    for (int x : a) {
        if (first == null || x > first) { second = first; first = x; }
        else if (x != first && (second == null || x > second)) second = x;
    }
    return second == null ? OptionalInt.empty() : OptionalInt.of(second);
}
// Streams version: Arrays.stream(a).boxed().distinct().sorted(Comparator.reverseOrder()).skip(1).findFirst()

How interviewers ask it“Can you remove duplicates from a list while keeping order in Java? Then walk me through the edge cases you would test.”

How do you remove duplicates from a list while keeping order?

CodingJava
Quick answerUse a LinkedHashSet, which removes duplicates and keeps insertion order, or distinct() on a stream.
Java
List<Integer> nums = List.of(3, 1, 3, 2, 1);
List<Integer> unique = new ArrayList<>(new LinkedHashSet<>(nums));  // [3, 1, 2]
List<Integer> unique2 = nums.stream().distinct().toList();         // [3, 1, 2]

How interviewers ask it“Coding-round task — implement a thread-safe Singleton in Java. Explain your approach before you write the code.”

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

CodingJava
Quick answerThe simplest correct options are an enum singleton (safe against serialization and reflection) or the holder idiom (lazy and thread-safe through class-initialisation guarantees).
Java
public enum AppConfig {
    INSTANCE;
    private final Properties props = load();
    public String get(String key) { return props.getProperty(key); }
}

public final class Registry {
    private Registry() {}
    private static class Holder { static final Registry INSTANCE = new Registry(); }
    public static Registry getInstance() { return Holder.INSTANCE; }   // lazy, no locking
}

In Spring applications, let the container manage singletons instead of writing your own.

CodingJava
Quick answerA BlockingQueue handles waiting and signalling for you: put blocks when the queue is full and take blocks when it is empty.
Java
BlockingQueue<Integer> queue = new ArrayBlockingQueue<>(10);

Thread producer = new Thread(() -> {
    try { for (int i = 1; i <= 20; i++) queue.put(i); queue.put(-1); }   // -1 = poison pill
    catch (InterruptedException e) { Thread.currentThread().interrupt(); }
});
Thread consumer = new Thread(() -> {
    try { for (int v; (v = queue.take()) != -1; ) System.out.println("Consumed " + v); }
    catch (InterruptedException e) { Thread.currentThread().interrupt(); }
});
producer.start(); consumer.start();

How interviewers ask it“Can you find duplicate elements in an array using a HashSet in Java? Then walk me through the edge cases you would test.”

How do you find duplicate elements in an array using a HashSet?

CodingJava
Quick answerSet.add returns false when the element is already present — one pass, O(n).
Java
static Set<Integer> duplicates(int[] a) {
    Set<Integer> seen = new HashSet<>(), dups = new LinkedHashSet<>();
    for (int x : a) if (!seen.add(x)) dups.add(x);
    return dups;
}
// duplicates(new int[]{4, 2, 4, 5, 2, 2}) -> [4, 2]
CodingJava
Quick answerLinkedHashMap with access order plus removeEldestEntry gives an O(1) LRU cache in a few lines. Mention that you can also build one from a HashMap plus a doubly linked list.
Java
class LRUCache<K, V> extends LinkedHashMap<K, V> {
    private final int capacity;
    LRUCache(int capacity) {
        super(capacity, 0.75f, true);      // true = access order
        this.capacity = capacity;
    }
    @Override protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
        return size() > capacity;
    }
}
// Not thread-safe: wrap access in a lock, or use Caffeine in production.

Practise with the free Java quiz

Multiple-choice questions with instant feedback. Takes about 10 minutes and shows exactly which concepts to revise.

Start the Java quiz →

Java interview FAQ

What Java questions are asked for freshers?
OOP pillars, JDK vs JRE vs JVM, == vs equals(), String immutability, static, final, method overloading vs overriding, abstract class vs interface, exception handling basics, ArrayList vs LinkedList, and simple programs like string reversal, palindrome and Fibonacci.
What Java questions are asked for 3–5 years of experience?
HashMap internals, equals/hashCode contract, ConcurrentHashMap, Streams and lambdas, Optional, generics and wildcards, the Java memory model, synchronized vs Lock, thread pools and CompletableFuture, garbage collectors, memory leaks, immutability, records, sealed classes and design patterns used in Spring applications.
Which Java version should I prepare for in 2026?
Prepare on Java 21 (LTS) and know the headline features of Java 25 (LTS, September 2025). Most companies run Java 17 or 21; interviewers expect you to know records, sealed classes, pattern matching for switch, text blocks and virtual threads.
Is Java still in demand in 2026?
Yes. Java remains a top-three language for backend jobs, especially with Spring Boot microservices, Kafka-based systems, Android and fintech. Virtual threads and fast startup options (GraalVM native images, CRaC) keep it relevant for cloud workloads.
AK
Written and reviewed by Abhishek Kumar
Founder, InterviewPitch · 10+ years in IT. Questions are collected from real interview rounds and refreshed regularly. Spotted an error? Tell us.