
Java Interview Questions for 5 Years Experience (2025 Edition)
If you’re preparing for a Java developer role with 5 years of experience, you’re expected to have more than just knowledge of core Java. You should understand Java 8+ features, multithreading, design patterns, memory management, and real-world problem-solving. This guide covers the most searched Java interview questions that recruiters commonly ask in 2025.
1. Explain the difference between HashMap
, LinkedHashMap
, and TreeMap
.
Feature | HashMap | LinkedHashMap | TreeMap |
---|---|---|---|
Order | No order | Insertion order | Sorted order |
Null Keys | 1 allowed | 1 allowed | Not allowed |
Performance | Fastest | Slightly slower | Slower |
Use Case | General use | Predictable iteration | Sorted data |
2. How does Java handle memory management?
Answer:
Java uses:
- Heap memory: For objects.
- Stack memory: For method calls and local variables.
- Garbage Collection (GC): Removes unused objects automatically.
You can monitor memory with tools like VisualVM, jconsole, orjstat
.
3. What is the difference between wait()
, sleep()
, and join()
?
wait()
: Releases lock, used for thread communication.sleep()
: Pauses thread but doesn’t release lock.join()
: Waits for another thread to finish.
Thread t = new Thread(() -> {});
t.start();
t.join(); // Waits for t to complete
4. What is a deadlock? How to prevent it?
Deadlock occurs when two or more threads wait for each other indefinitely, holding locks.
Prevention:
- Use a consistent locking order.
- Use
tryLock()
with timeout. - Avoid nested locks when possible.
5. How are design patterns used in Java?
Common patterns:
- Singleton – One instance.
- Factory – Object creation logic.
- Strategy – Switch behaviors dynamically.
- Observer – Event handling system.
- Decorator – Add responsibilities dynamically.
public class Singleton {
private static final Singleton INSTANCE = new Singleton();
private Singleton() {}
public static Singleton getInstance() {
return INSTANCE;
}
}
6. What’s the difference between Callable
and Runnable
?
Feature | Runnable | Callable |
---|---|---|
Return | void | Future<T> |
Exceptions | Cannot throw checked | Can throw exceptions |
Use Case | Simple threads | Task with result |
7. How do you implement a thread-safe singleton?
Double-checked locking:
public class SafeSingleton {
private static volatile SafeSingleton instance;
private SafeSingleton() {}
public static SafeSingleton getInstance() {
if (instance == null) {
synchronized (SafeSingleton.class) {
if (instance == null) {
instance = new SafeSingleton();
}
}
}
return instance;
}
}
8. What are Stream operations in Java 8?
- Intermediate:
map()
,filter()
,sorted()
- Terminal:
collect()
,forEach()
,count()
List<String> list = Arrays.asList("a", "b", "c");
list.stream().filter(s -> s.equals("b")).forEach(System.out::println);
9. Explain SOLID principles in Java.
- S – Single Responsibility
- O – Open/Closed
- L – Liskov Substitution
- I – Interface Segregation
- D – Dependency Inversion
These principles are vital for writing scalable, testable, and clean code in large projects.
10. What are functional interfaces and how are they useful?
A functional interface has one abstract method and is used in lambda expressions.
@FunctionalInterface
interface MyFunc {
int operate(int a, int b);
}
11. What is Optional
and when should you use it?
Optional helps avoid NullPointerException
.
Optional<String> name = Optional.ofNullable(null);
System.out.println(name.orElse("Default"));
Use Optional
in method returns where null
might be expected.
12. How does garbage collection work in Java?
Java GC uses algorithms like:
- Mark and Sweep
- Generational GC
- G1 GC (Garbage First)
Use System.gc()
only when necessary. JVM mostly handles it well.
13. How is exception handling used in real-world Java?
Handle exceptions gracefully, log important info, and avoid exposing stack traces to users.
try {
// risky code
} catch (IOException e) {
logger.error("IO failed", e);
} finally {
// cleanup
}
14. Describe Java memory leaks and how to avoid them.
Even with GC, memory leaks happen due to:
- Static references
- Unclosed resources
- Listeners that aren’t removed
Tools: VisualVM, JProfiler
Best Practices:
- Use
try-with-resources
- Clean up listeners
15. Common real-time scenario question
Q: How would you handle millions of records in a REST API?
Answer:
- Use pagination (
Pageable
) - Use streaming API if needed
- Cache frequent queries
- Tune JVM memory
16. What are best practices for writing Java code with 5 years of experience?
- Follow SOLID and clean code principles
- Use
var
wisely (Java 10+) - Leverage Streams for readability
- Use meaningful logging (SLF4J, Logback)
- Write unit tests (JUnit 5, Mockito)
17. Describe how you manage code quality in your projects.
Answer:
- Code Reviews using GitHub/GitLab
- Static Analysis: SonarQube
- Code Formatters: Checkstyle
- Continuous Integration: Jenkins, GitHub Actions
18. What are strong Java 8+ features to master at this level?
- Stream API
- Functional programming
- Optional
- Method references
Collectors.groupingBy
- LocalDate/Time APIs
19. Describe how equals() and hashCode() are related.
Both are critical for hash-based collections like HashMap
and HashSet
.
@Override
public boolean equals(Object o) {
// equality logic
}
@Override
public int hashCode() {
// must match equals logic
}
20. What’s your approach to debugging and troubleshooting Java applications?
- Use IDE tools like breakpoints & watchpoints
- Read logs
- Use
jstack
,jmap
,VisualVM
- Profiling tools for memory/cpu issues
- Ask “Why” recursively
Conclusion
By 5 years into your Java career, you should demonstrate a strong command over core and advanced concepts, write clean, maintainable code, and debug complex issues. These java interview questions for 5 years experience are designed to reflect that real-world readiness and go beyond textbook answers. Download Java
- How to Use Arrays in Java (with Code Examples for Beginners)
- Compilation in Java – How It Works with Execution Flow, Steps, and Example
- How to Use loops in Java: For, While, Do‑While Explained
- How to Use If Else Statement in Java (With Examples)
- How to Understand Object-Oriented Programming in Java Easily