Advanced Java Interview Questions

Top 50 Advanced Java Interview Questions and Answers for Experienced Developers (2025 Updated)

If you’re an experienced Java developer preparing for a product-based or enterprise interview, you know the challenge — interviewers go beyond syntax.

They want to test your understanding of how Java works under the hood — from memory management and multithreading to functional programming and performance optimization.

This guide contains 50 advanced Java interview questions with detailed explanations, real-world examples, and the latest Java 8+ concepts — written in a human, conversational tone to make learning natural and enjoyable.


⚙️ Section 1: Core Java & OOP Deep Dive


1️⃣ What is the difference between an Abstract Class and an Interface?

An abstract class in Java provides a base blueprint for other classes to extend, while an interface defines a contract of methods that implementing classes must fulfill.

Key Differences:

FeatureAbstract ClassInterface
MethodsCan have both abstract and concrete methodsBefore Java 8, only abstract; from Java 8, can include default/static methods
Multiple InheritanceNot allowedAllowed
VariablesCan have instance variablesOnly public static final constants
ConstructorYesNo

When to Use:

  • Use an abstract class when classes share common state or implementation.
  • Use an interface when you just need to define a behavior contract (e.g., Comparable, Runnable).

Example:

interface Payment {
   void pay();
}

abstract class CreditCardPayment implements Payment {
   void validateCard() { System.out.println("Card validated"); }
}

2️⃣ Explain Functional Interfaces and Why They Are Important.

A Functional Interface is an interface that has exactly one abstract method.
These interfaces are the backbone of lambda expressions introduced in Java 8.

Examples:
Runnable, Callable, Consumer, Supplier, Predicate, Function.

Example:

@FunctionalInterface
interface Calculator {
    int add(int a, int b);
}

Calculator calc = (x, y) -> x + y;
System.out.println(calc.add(10, 20));

Why It Matters:

  • Enables cleaner and more functional code.
  • Simplifies usage of Streams, async tasks, and event-driven programming.

3️⃣ Difference Between == and .equals() in Java.

  • == compares memory addresses (object references).
  • .equals() compares content (object values).

Example:

String s1 = new String("Java");
String s2 = new String("Java");

System.out.println(s1 == s2);      // false
System.out.println(s1.equals(s2)); // true

4️⃣ What is Immutability and How Do You Create Immutable Objects?

An immutable object cannot be changed after creation — any modification creates a new instance.

Steps to make a class immutable:

  1. Declare the class as final.
  2. Make all fields private and final.
  3. Do not provide setters.
  4. Return deep copies in getters.

Example:

public final class Employee {
   private final String name;
   public Employee(String name) { this.name = name; }
   public String getName() { return name; }
}

Why Important?

  • Thread-safe by design
  • Ideal for caching and concurrent environments

5️⃣ Explain Wrapper Classes in Java.

Wrapper classes convert primitive types into objects (Autoboxing).

Example:

int num = 10;
Integer wrappedNum = num; // Autoboxing
int value = wrappedNum;   // Unboxing

They’re crucial for Collections (ArrayList<Integer>) and Streams, as generics don’t support primitives.


6️⃣ Difference Between String, StringBuilder, and StringBuffer.

FeatureStringStringBuilderStringBuffer
MutabilityImmutableMutableMutable
Thread-safetyYes (Immutable)NoYes
SpeedSlowestFastestModerate

In interviews, prefer StringBuilder for single-threaded performance and StringBuffer for thread-safe operations.


🧵 Section 2: Exception Handling & Multithreading


7️⃣ Difference Between Checked and Unchecked Exceptions

  • Checked: Known at compile-time (IOException, SQLException).
  • Unchecked: Occur at runtime (NullPointerException, ArithmeticException).

✅ Example:

// Checked Exception
try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); }

// Unchecked Exception
int x = 10 / 0; // ArithmeticException

8️⃣ Explain throw vs throws.

  • throw: Used to throw an exception manually.
  • throws: Declares that a method may throw exceptions.

✅ Example:

void demo() throws IOException {
   throw new IOException("I/O failed");
}

9️⃣ Difference Between wait(), sleep(), and yield().

MethodBelongs ToReleases LockPurpose
wait()Object class✅ YesWait until notified
sleep()Thread class❌ NoPause for time
yield()Thread class❌ NoSuggests to scheduler

🔟 Explain synchronized vs Lock interface.

  • synchronized is a keyword for basic thread safety.
  • Lock (in java.util.concurrent.locks) provides explicit locking with fairness control.

✅ Example:

Lock lock = new ReentrantLock();
lock.lock();
try {
  // critical section
} finally {
  lock.unlock();
}

11️⃣ What is a Daemon Thread?

A daemon thread runs in the background for JVM operations (e.g., garbage collection).
It ends when all user threads finish.

✅ Example:

Thread t = new Thread(() -> System.out.println("Daemon running"));
t.setDaemon(true);
t.start();

🧠 Section 3: Memory Management & JVM Internals


12️⃣ Explain the JVM Architecture.

Components:

  1. Class Loader Subsystem – Loads classes.
  2. Runtime Data Areas – Stack, Heap, Metaspace.
  3. Execution Engine – Interprets bytecode.
  4. Garbage Collector – Frees memory.

13️⃣ What is a Memory Leak in Java?

Occurs when objects are no longer used but not garbage-collected due to active references.

✅ Example:

static List<Object> cache = new ArrayList<>();
public void add() { cache.add(new Object()); } // never cleared

14️⃣ Explain Garbage Collection (GC) Algorithms.

  • Serial GC: Single-threaded, small apps.
  • Parallel GC: Multiple threads.
  • G1 GC: Balances throughput and pause time.
  • ZGC / Shenandoah: Low-latency GCs for large-scale systems.

15️⃣ Explain ClassLoader Hierarchy.

Class loading follows Delegation Model:

  • Bootstrap → Extension → Application Loader
    Each loader delegates to the parent before loading itself.

🔄 Section 4: Java Collections & Stream API


16️⃣ Difference Between HashMap and ConcurrentHashMap.

FeatureHashMapConcurrentHashMap
Thread Safety❌ No✅ Yes
Null Keys1None
PerformanceFaster (single-threaded)Optimized for multi-threaded

17️⃣ What’s the Difference Between map() and flatMap()?

  • map() transforms each element.
  • flatMap() flattens nested collections.

✅ Example:

Stream.of(List.of(1,2), List.of(3,4))
      .flatMap(Collection::stream)
      .forEach(System.out::println);

18️⃣ What is Optional and How It Prevents NPE?

Optional is a wrapper to handle null safely.

✅ Example:

Optional<String> name = Optional.ofNullable(null);
System.out.println(name.orElse("Default"));

19️⃣ What are Collectors in Stream API?

They collect Stream results into a container.

✅ Example:

List<String> list = Stream.of("Java", "Spring").collect(Collectors.toList());

20️⃣ How Does the Stream API Improve Performance?

  • Enables parallel execution with parallelStream().
  • Reduces boilerplate with filter-map-reduce patterns.
  • Uses lazy evaluation to optimize runtime.

🧩 Section 5: Concurrency & Functional Programming


21️⃣ What is CompletableFuture?

An advanced Future that supports async callbacks.

✅ Example:

CompletableFuture.supplyAsync(() -> "Task")
                 .thenApply(result -> result + " completed")
                 .thenAccept(System.out::println);

22️⃣ What are Lambda Expressions?

They simplify anonymous functions.

✅ Example:

Runnable r = () -> System.out.println("Running thread");

23️⃣ What is a Predicate?

Represents a condition returning a boolean.
Useful in filtering.

✅ Example:

Predicate<Integer> isEven = n -> n % 2 == 0;

24️⃣ What is a Supplier?

Supplies values without taking input.

✅ Example:

Supplier<Double> random = Math::random;

25️⃣ What is a Function Interface?

Takes one argument and returns a result.

✅ Example:

Function<String, Integer> length = s -> s.length();

💼 Section 6: Design Patterns & Architecture


26️⃣ Explain Singleton Pattern.

Ensures only one instance exists.

class Singleton {
   private static final Singleton instance = new Singleton();
   private Singleton() {}
   public static Singleton getInstance() { return instance; }
}

27️⃣ What is Dependency Injection (DI)?

Injects dependencies instead of creating them inside a class — a key concept in Spring.


28️⃣ What is the Factory Pattern?

Creates objects without exposing logic to the client.


29️⃣ Explain Builder Pattern.

Used for constructing complex objects step-by-step.
Common in StringBuilder, Lombok @Builder.


30️⃣ What is the Strategy Pattern?

Defines a family of algorithms and makes them interchangeable at runtime.


⚡ Section 7: Advanced Topics


31️⃣ Explain Nashorn JavaScript Engine.

A JS runtime in JVM that allows executing JS code in Java. (Deprecated from Java 15).


32️⃣ Explain Default Methods in Interfaces.

Default methods let you add new methods to interfaces without breaking implementations.


33️⃣ What is Base64 Encoding/Decoding?

Introduced in Java 8:

String encoded = Base64.getEncoder().encodeToString("Java".getBytes());
String decoded = new String(Base64.getDecoder().decode(encoded));

34️⃣ What are Atomic Variables?

Thread-safe variables using low-level CAS (Compare-And-Swap).
AtomicInteger, AtomicBoolean.


35️⃣ What are Parallel Streams?

Used for multi-core processing — divides data into substreams.


🔐 Section 8: Microservices & Performance


36️⃣ What is REST and Why Is It Popular?

REST (Representational State Transfer) is a lightweight API design style using HTTP methods like GET, POST, PUT, DELETE.


37️⃣ Explain SOAP vs REST.

  • SOAP: Protocol, strict structure, XML.
  • REST: Simpler, JSON-friendly, used in Spring Boot APIs.

38️⃣ What is Thread Dump?

Snapshot of all running threads — useful for diagnosing deadlocks.


39️⃣ What is a Deadlock?

Occurs when two threads wait for each other indefinitely.


40️⃣ What is the Volatile Keyword?

Ensures visibility of variable updates across threads. Prevents caching issues.


41️⃣ What is Serialization and Deserialization?

  • Serialization: Converts objects into byte streams.
  • Deserialization: Converts byte streams into objects.

42️⃣ What is the Difference Between Comparable and Comparator?

  • Comparable: Defines natural order within the class.
  • Comparator: Defines external comparison logic.

43️⃣ What is Fail-Fast vs Fail-Safe?

  • Fail-Fast: Throws ConcurrentModificationException (ArrayList).
  • Fail-Safe: Works on copy (ConcurrentHashMap).

44️⃣ What is Transient Keyword?

Marks a field that should not be serialized.


45️⃣ What is Reflection in Java?

Used to inspect and modify class behavior at runtime using java.lang.reflect.


46️⃣ What are JVM Tuning Parameters?

You can adjust heap size, GC type, and performance:
-Xms512m -Xmx2g -XX:+UseG1GC


47️⃣ What are Memory Leaks in Threads?

When thread-local variables prevent garbage collection.


48️⃣ What is a Thread Pool?

A collection of reusable threads used by ExecutorService for concurrent tasks.


49️⃣ What is a Future Interface?

Used to get the result of an asynchronous computation.


50️⃣ How to Improve Java Application Performance?

  • Use Streams wisely
  • Minimize synchronization
  • Use caching (EhCache, Caffeine)
  • Tune JVM parameters
  • Optimize SQL queries

🧭 Conclusion

These 50 advanced Java interview questions prepare you for high-level discussions on architecture, performance, and modern Java features.

Mastering these will not only help you crack interviews but also improve your day-to-day development confidence in enterprise projects.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply