Chapter 2 - Java Core
Chapter 2 – Java Core (Questions 11–25)
Question 11
What are the main features introduced in Java 17 and Java 21?
Why They Ask
They want to know whether you keep your Java knowledge up to date.
Model Answer
Java has evolved significantly over the last few LTS releases.
Java 17
- Sealed Classes
- Pattern Matching for
instanceof - Records (standard)
- Improved Garbage Collectors
- Strong encapsulation of JDK internals
Example:
if (obj instanceof String s) {
System.out.println(s.length());
}
Java 21
- Virtual Threads (Project Loom)
- Record Patterns
- Pattern Matching for switch
- Sequenced Collections
- String Templates (Preview)
- Structured Concurrency (Preview)
Virtual Threads are probably the biggest improvement because they allow applications to handle millions of concurrent tasks without creating millions of platform threads.
Follow-up
- Have you used Virtual Threads?
- When would you use them?
- Are they a replacement for reactive programming?
Interview Tip
Mention that your recent Spring Boot projects use Java 21, showing you stay current with modern Java.
Question 12
Explain the JVM memory model.
Model Answer
The JVM memory is divided into several areas.
Heap
├── Young Generation
│ ├── Eden
│ ├── Survivor 0
│ └── Survivor 1
│
└── Old Generation
Metaspace
Thread Stack
PC Register
Native Method Stack
Heap
Stores objects.
Shared among all threads.
Stack
Stores
- local variables
- method calls
- references
Each thread has its own stack.
Metaspace
Stores
- class metadata
- method information
Since Java 8 it replaced PermGen.
Example
Person p = new Person();
Reference (Stack)
│
▼
Object (Heap)
Common Mistake
Many candidates incorrectly say objects are stored on the stack.
Only primitive local variables live directly on the stack.
Question 13
Explain how Garbage Collection works.
Model Answer
Garbage Collection automatically frees memory occupied by objects that are no longer reachable.
Example:
Person p = new Person();
p = null;
The object becomes eligible for GC.
GC typically works in phases:
- Mark
- Sweep
- Compact
Modern collectors include
- G1GC
- ZGC
- Shenandoah
G1GC
Default in modern Java.
Designed for large heaps.
ZGC
Ultra-low latency.
Pause times usually under 10ms.
Useful for financial systems.
Follow-up
Which GC would you choose for a microservice?
Answer:
Usually G1GC unless extremely low latency is required.
Question 14
Explain equals() and hashCode().
Model Answer
equals() determines logical equality.
hashCode() determines which bucket an object belongs to in a HashMap.
Both methods must obey the contract:
If
a.equals(b)
then
a.hashCode() == b.hashCode()
must also be true.
Example:
public class User {
private String email;
@Override
public boolean equals(Object obj) {
...
}
@Override
public int hashCode() {
...
}
}
Common interview question:
Why override both?
Because HashMap first compares hashCode, then equals.
Question 15
HashMap vs ConcurrentHashMap
Model Answer
HashMap
- not thread-safe
- faster
- suitable for single-threaded use
ConcurrentHashMap
- thread-safe
- supports concurrent reads
- fine-grained locking
- avoids locking the entire map
Example:
ConcurrentHashMap<String, User> users =
new ConcurrentHashMap<>();
When working with Spring Boot services receiving many concurrent requests, ConcurrentHashMap is often a better choice for shared caches.
Question 16
ArrayList vs LinkedList
Model Answer
| ArrayList | LinkedList |
|---|---|
| Dynamic array | Doubly linked list |
| Fast random access | Slow random access |
| Fast iteration | Slower iteration |
| Slow insertion in middle | Fast insertion |
Time complexity
ArrayList
get() O(1)
insert() O(n)
remove() O(n)
LinkedList
get() O(n)
insert() O(1)
Most enterprise applications should prefer ArrayList.
Question 17
What happens internally when you put an object into a HashMap?
Model Answer
Example:
map.put(key, value);
Steps:
-
Calculate hashCode()
-
Calculate bucket index
-
Find bucket
-
If empty
Store object
Otherwise
Compare keys using equals()
If same key
Replace value
Else
Create linked list (or tree if bucket becomes large)
Since Java 8
Large buckets become Red-Black Trees
instead of linked lists.
Complexity improves from
O(n)
to
O(log n)
Question 18
Explain Java Streams.
Model Answer
Streams provide a declarative way to process collections.
Example
users.stream()
.filter(User::isActive)
.map(User::getEmail)
.sorted()
.toList();
Benefits
- readable
- less boilerplate
- supports parallel processing
- functional programming style
Difference
Collection stores data.
Stream processes data.
Question 19
What is the difference between map() and flatMap()?
Model Answer
Suppose
List<List<String>>
Using map
Result
Stream<List<String>>
Using flatMap
Stream<String>
Example
students.stream()
.flatMap(s -> s.getCourses().stream())
Very common in Spring Boot applications.
Question 20
Explain Optional.
Model Answer
Optional helps avoid NullPointerException.
Example
Instead of
if(user != null)
Use
Optional<User>
Example
return repository.findById(id)
.map(UserDto::from)
.orElseThrow();
Avoid
Optional<String> name;
as a field.
Use Optional mainly as a return type.
Question 21
Explain Java Concurrency.
Model Answer
Concurrency allows multiple tasks to make progress simultaneously.
Important classes
- Thread
- Runnable
- Callable
- ExecutorService
- CompletableFuture
- ForkJoinPool
Modern Java also supports
Virtual Threads.
Example
ExecutorService executor =
Executors.newFixedThreadPool(10);
Question 22
What is the difference between synchronized, Lock, and AtomicInteger?
Model Answer
synchronized
Simple
Automatic lock management
synchronized(this) {
}
ReentrantLock
More flexible
Supports
- timeout
- fairness
- tryLock()
AtomicInteger
Lock-free
Uses CAS
Very fast
counter.incrementAndGet();
For high-performance counters, AtomicInteger is usually preferred.
Question 23
Explain CompletableFuture.
Model Answer
CompletableFuture enables asynchronous programming.
Example
CompletableFuture<User> future =
CompletableFuture.supplyAsync(
() -> service.loadUser(id)
);
Benefits
- async execution
- chaining
- exception handling
- combining multiple async tasks
Useful in
- calling multiple REST services
- parallel database queries
Question 24
Explain immutability.
Model Answer
Immutable objects cannot change after creation.
Example
public final class User {
private final String name;
}
Benefits
- thread-safe
- easier debugging
- predictable behavior
Java Records are immutable by default.
Example
public record User(
Long id,
String name
){}
Question 25
What are the most common performance problems in Java applications?
Model Answer
Some common issues include:
Excessive object creation
Creates unnecessary garbage collection pressure.
N+1 Database Queries
Frequently seen with JPA and Hibernate when relationships are lazily loaded.
Inefficient SQL
Missing indexes, full table scans, or fetching more data than necessary.
Blocking I/O
Threads waiting on slow database or network calls reduce throughput.
Memory Leaks
Objects retained unintentionally, often through static collections, caches, or listeners.
Poor Collection Choices
Using the wrong data structure can significantly impact performance.
Excessive Synchronization
Overusing synchronized can create contention and reduce scalability.
Performance Improvements I've Applied
In my projects, I have focused on:
- Optimizing SQL queries and adding appropriate indexes.
- Reducing unnecessary Elasticsearch/OpenSearch queries.
- Improving CI/CD pipelines to shorten deployment times.
- Designing stateless microservices for better horizontal scalability.
- Using asynchronous processing where appropriate to improve throughput.
Common Follow-up Questions for This Chapter
Be prepared for these additional Java questions:
- What is the Java Memory Model (JMM)?
- What is the
volatilekeyword? - How does Compare-And-Swap (CAS) work?
- Explain the happens-before relationship.
- Difference between
CallableandRunnable. - Why is
Stringimmutable? - What is string pooling?
- How does
ConcurrentHashMapachieve thread safety? - What are Soft, Weak, and Phantom references?
- When would you choose Virtual Threads over traditional thread pools?
Chapter Summary
After studying this chapter, you should be able to discuss:
- Modern Java (17/21) features
- JVM memory management
- Garbage collection strategies
- Collections and their internal implementations
- Streams and functional programming
- Concurrency and asynchronous programming
- Immutability and records
- Performance optimization techniques
- Best practices for writing scalable Java applications
In the next chapter, we'll cover Spring & Spring Boot (Questions 26–40), including dependency injection, bean lifecycle, Spring MVC, Spring Data JPA, transactions, security, testing, and performance tuning—topics that are central to Senior and Staff Backend Engineer interviews.