Top 10 Java Interview Questions and Answers for 2025
Preparing for a Java interview in 2025? The Java ecosystem continues to evolve, and companies seek developers with strong problem-solving skills and up-to-date knowledge. Here are the top 10 Java interview questions with answers to help you ace your next interview.
1. What are the main features introduced in Java 17?
Answer: Java 17 (LTS) introduced several key features, including:
-
Sealed Classes
-
Pattern Matching for
switch
-
Strongly Encapsulated JDK Internals
-
New macOS Rendering Pipeline
-
Deprecation of Security Manager
Example:
sealed class Vehicle permits Car, Bike {}
final class Car extends Vehicle {}
final class Bike extends Vehicle {}
2. What is the difference between var
, final var
, and record
in Java?
Answer:
-
var
is used for local variable type inference. -
final var
ensures that the variable cannot be reassigned. -
record
is a new type for immutable data classes.
Example:
record Person(String name, int age) {}
Person p = new Person("Alice", 30);
System.out.println(p.name()); // Alice
3. How does Java handle memory management?
Answer: Java uses Automatic Garbage Collection (GC) with different collectors like:
-
G1 GC (Default since Java 9)
-
ZGC (Low-latency GC introduced in Java 11)
-
Shenandoah GC (Highly concurrent GC)
4. Explain the difference between ExecutorService
and ForkJoinPool
.
Answer:
-
ExecutorService
is for managing a fixed pool of threads. -
ForkJoinPool
is for parallel processing and divide-and-conquer algorithms.
Example:
ForkJoinPool pool = new ForkJoinPool();
5. What are Virtual Threads in Java?
Answer: Virtual Threads (Project Loom) provide lightweight, scalable concurrency.
Example:
Thread.startVirtualThread(() -> System.out.println("Hello Virtual Threads!"));
6. What is the difference between CompletableFuture
and Reactive Streams
?
Answer:
-
CompletableFuture
handles asynchronous programming. -
Reactive Streams
(Project Reactor) provides backpressure support.
7. How to implement a Kafka consumer in Java?
Answer:
Properties props = new Properties();
props.put("bootstrap.servers", "localhost:9092");
Consumer<String, String> consumer = new KafkaConsumer<>(props);
consumer.subscribe(Collections.singletonList("my-topic"));
8. What is the difference between HashMap
and ConcurrentHashMap
?
Answer:
-
HashMap
is not thread-safe. -
ConcurrentHashMap
is optimized for concurrent read/write operations.
9. How to optimize performance in Spring Boot applications?
Answer:
-
Use @Transactional to manage DB transactions efficiently.
-
Enable caching with
@Cacheable
. -
Use Connection Pooling (HikariCP).
10. What are the best practices for writing clean Java code?
Answer:
-
Follow SOLID principles.
-
Use meaningful variable names.
-
Avoid redundant code (DRY principle).
-
Use logging frameworks (Log4j, SLF4J).
No comments:
Post a Comment