Skip to content

Java Interview Questions for 7 Years Experience

40 questions with answers for candidates with 7 years of experience — 17 medium, 23 hard.

What interviewers expect: 7 years experience

Seven year engineers are expected to act as tech leads or principal engineers. Interviews focus on architecture of systems you owned, migration from monolith to microservices, observability, security, cost and team practices. You should explain how you made decisions with trade-offs, guided other engineers and improved delivery quality across services.

This set is weighted towards JDBC, Hibernate and JPA (10), Multithreading and Concurrency (8), Java 8+ Features and Streams (6), Collections Framework (5).

Architecture and migrations Observability and reliability Security and compliance Team leadership
Solved at this levelStart practicing
3 QUESTIONS FREESign up to unlock the full question bank and track your progress.Unlock every question and answer, then continue practising company-wise and package-wise.
3 questions free Unlock the rest in seconds
01

Run two tasks in parallel with CompletableFuture and combine their results.

Save to ▾
Show answer
Use a dedicated executor for I/O work. ExecutorService pool = Executors.newFixedThreadPool(4); CompletableFuture<User> user = CompletableFuture.supplyAsync(() -> userApi.get(id), pool); CompletableFuture<List<Order>> orders = CompletableFuture.supplyAsync(() -> orderApi.list(id), pool); Profile p = user.thenCombine(orders, Profile::new) .orTimeout(2, TimeUnit.SECONDS) .join();
02

Group a list of orders by city and sum the amount per city.

Save to ▾
Show answer
Use groupingBy with a summing collector. Map<String, Double> totals = orders.stream() .collect(Collectors.groupingBy( Order::city, TreeMap::new, Collectors.summingDouble(Order::amount))); TreeMap keeps cities sorted. For money, store amounts as long paise or BigDecimal and use Collectors.reducing with BigDecimal::add.
03

Write a custom unchecked exception and a Spring handler that returns HTTP 404.

Save to ▾
Show answer
Define the exception, then map it centrally. public class NotFoundException extends RuntimeException { public NotFoundException(String msg) { super(msg); } } @RestControllerAdvice public class ApiErrors { @ExceptionHandler(NotFoundException.class) public ProblemDetail notFound(NotFoundException e) { return ProblemDetail.forStatusAndDetail( HttpStatus.NOT_FOUND, e.getMessage()); } }
04

Implement a producer-consumer using BlockingQueue.

Save to ▾
Show answer
BlockingQueue handles waiting and signalling for you. BlockingQueue<Integer> q = new ArrayBlockingQueue<>(10); Runnable producer = () -> { for (int i = 0; i < 100; i++) { try { q.put(i); } catch (InterruptedException e) { Thread.currentThread().interrupt(); return; } } }; Runnable consumer = () -> { try { while (true) System.out.println(q.take()); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }; put blocks when full and take blocks when empty.
05

Write code that runs 10,000 blocking tasks using virtual threads.

Save to ▾
Show answer
Use the virtual-thread-per-task executor in Java 21. try (var ex = Executors.newVirtualThreadPerTaskExecutor()) { for (int i = 0; i < 10_000; i++) { int id = i; ex.submit(() -> { Thread.sleep(Duration.ofMillis(200)); return id; }); } } // close() waits for all tasks All tasks finish in about 200 ms because blocked virtual threads free their carriers.
06

Explain pattern matching for switch and record patterns in Java 21.

Save to ▾
Show answer
Pattern matching for switch lets a case match on type and bind a variable, such as case Circle c -> Math.PI * c.r() * c.r(). Record patterns deconstruct a record directly: case Point(int x, int y). Guards add conditions with when. With sealed types the compiler checks the switch is exhaustive, so adding a new subtype causes a compile error where it is not handled.
07

A thread pool fills up and tasks get rejected during traffic spikes. How do you handle it?

Save to ▾
Show answer
First check why tasks are slow, since slow tasks fill pools. Then choose a policy: a bounded queue with CallerRunsPolicy applies backpressure by running the task in the submitting thread; otherwise return a fast 503 so clients retry. Tune pool and queue sizes from load tests. Never use an unbounded queue, because it hides the problem until memory runs out.
08

What is the N+1 select problem in Hibernate and how do you fix it?

Save to ▾
Show answer
N+1 happens when you load N parent entities with one query and then a lazy association triggers one extra query per parent, giving N+1 queries. Fix it with a JOIN FETCH in JPQL, an @EntityGraph on the repository method, or batch fetching with @BatchSize or hibernate.default_batch_fetch_size. Detect it by enabling SQL logging or using a query count assertion in tests.
09

After moving to virtual threads, throughput did not improve and some requests stalled. What could cause it?

Save to ▾
Show answer
Common causes are pinning, where a virtual thread blocks inside a synchronized block or native call and holds its carrier thread; this was largely fixed in Java 24 for synchronized, but native calls still pin. Another cause is a fixed downstream bottleneck such as a small JDBC pool, so more threads just wait. Detect pinning with JFR events, use ReentrantLock in older versions and size pools to real capacity.
10

A stream over a list of orders is slow in a hot path. How do you analyse it?

Save to ▾
Show answer
Profile first with JFR or async-profiler to confirm the stream is the hotspot. Check for repeated work like calling sorted() inside a loop, boxing overhead with Stream of Integer instead of IntStream, or re-streaming the same list many times. Cache computed maps, use primitive streams and, if still slow, a plain loop can be clearer and faster for very hot code.
11

Tell me about a time you improved performance by choosing a better data structure.

Save to ▾
Show answer
Situation: a report job matching 2 lakh transactions to customers took 40 minutes. Task: bring it under the 5 minute window. Action: profiling showed list.contains() inside a loop, which was O(n squared). I loaded customer ids into a HashSet and grouped transactions with a HashMap. Result: runtime dropped to 50 seconds and I shared the pattern in our team wiki.
12

A HashMap shared by many threads sometimes loses updates. How do you fix it?

Save to ▾
Show answer
HashMap is not thread safe, so concurrent put calls can overwrite each other. Replace it with ConcurrentHashMap and use atomic methods instead of get-then-put, for example counts.merge(key, 1, Integer::sum) or computeIfAbsent for lazy creation. Collections.synchronizedMap also works but locks the whole map, which hurts throughput under contention.
13

What is a ClassLoader and what is the delegation model?

Save to ▾
Show answer
A ClassLoader loads .class files into the JVM. The main loaders are Bootstrap (core classes), Platform (formerly Extension) and Application (classpath). In the parent delegation model a loader first asks its parent to load a class and only loads it itself if the parent cannot. This prevents user code from replacing core classes like java.lang.String.
14

Production shows Connection is not available, request timed out after 30000ms from HikariCP. What do you check?

Save to ▾
Show answer
The pool is exhausted. Check for connection leaks, where code holds connections without closing, by setting leakDetectionThreshold. Look for long transactions doing remote calls inside @Transactional, slow queries holding connections and a pool size too small for the thread count. Fix leaks, move external calls outside transactions, optimise slow queries and then size the pool from load tests.
15

What are the key patterns used in microservices built with Spring Boot?

Save to ▾
Show answer
Common patterns are API gateway (Spring Cloud Gateway) for routing and auth, service discovery or Kubernetes services, externalised config, circuit breaker and retry with Resilience4j, database per service, event-driven communication with Kafka, saga for distributed transactions, and observability with Micrometer, tracing and centralised logs. Each service owns its data and deploys independently.
16

What is the difference between HashMap and ConcurrentHashMap?

Save to ▾
Show answer
HashMap is not thread safe; concurrent writes can lose data or corrupt the structure. ConcurrentHashMap supports full concurrency: reads are lock free and writes use CAS or lock a single bin, so threads rarely block each other. It does not allow null keys or values. It also provides atomic compound operations such as computeIfAbsent and merge, which avoid check-then-act races.
17

When should you avoid parallel streams?

Save to ▾
Show answer
Parallel streams use the common ForkJoinPool and help only for large, CPU-bound, stateless work on sources that split well, like arrays and ArrayList. Avoid them for small data, I/O or blocking calls, LinkedList or iterate() sources, ordered operations like limit and findFirst, and shared mutable state. In a web server they compete for the same common pool, so measure before using them.
18

Two users booking the last seat both succeed. How do you prevent double booking?

Save to ▾
Show answer
This is a race between read and write. Use a database guarantee: a unique constraint on seat and show, an atomic conditional update like UPDATE seats SET status = 'BOOKED' WHERE id = ? AND status = 'FREE' and check the affected row count, or pessimistic locking with SELECT FOR UPDATE. Optimistic locking with a version column also works, retrying or failing the loser.
19

What is optimistic versus pessimistic locking in JPA?

Save to ▾
Show answer
Optimistic locking adds a @Version column; on update Hibernate checks the version and throws OptimisticLockException if another transaction changed the row, so you retry. It suits low contention. Pessimistic locking uses SELECT FOR UPDATE through LockModeType.PESSIMISTIC_WRITE, blocking others until commit; it suits high contention on the same rows, like seat booking, but can reduce throughput.
20

How would you write a simple thread safe rate limiter in Java?

Save to ▾
Show answer
A token bucket with synchronized refill is simple and correct. class RateLimiter { private final long capacity, refillPerSec; private double tokens; private long last = System.nanoTime(); RateLimiter(long cap, long rps) { capacity = cap; refillPerSec = rps; tokens = cap; } synchronized boolean tryAcquire() { long now = System.nanoTime(); tokens = Math.min(capacity, tokens + (now - last) / 1e9 * refillPerSec); last = now; if (tokens >= 1) { tokens--; return true; } return false; } } Across servers, keep the bucket in Redis.
21

What are transaction isolation levels and which problems do they prevent?

Save to ▾
Show answer
Read Uncommitted allows dirty reads. Read Committed prevents dirty reads and is the default in PostgreSQL and SQL Server. Repeatable Read also prevents non-repeatable reads and is the MySQL InnoDB default. Serializable prevents phantom reads too but reduces concurrency. Choose the lowest level that keeps data correct, and use explicit locking for specific hot rows.
22

Write a JDBC batch insert for a list of products.

Save to ▾
Show answer
Batching sends many rows in one round trip. String sql = "INSERT INTO product(name, price) VALUES (?, ?)"; try (Connection c = ds.getConnection(); PreparedStatement ps = c.prepareStatement(sql)) { c.setAutoCommit(false); int n = 0; for (Product p : products) { ps.setString(1, p.name()); ps.setLong(2, p.price()); ps.addBatch(); if (++n % 500 == 0) ps.executeBatch(); } ps.executeBatch(); c.commit(); }
23

How would you split a monolith into microservices?

Save to ▾
Show answer
Do not split everything at once. Identify bounded contexts with the business, such as orders, payments and catalogue, and pick a module with clear boundaries and high change rate first. Use the strangler fig pattern: route its traffic through a gateway to the new service, give it its own database and sync data through events. Add observability and CI/CD before scaling out further.
24

What is the Liskov Substitution Principle? Give an example of breaking it.

Save to ▾
Show answer
LSP says any subclass object must be usable wherever the parent is expected without breaking behaviour. A classic violation is Square extends Rectangle: setting width also changes height, so code that sets width 5 and height 4 and expects area 20 fails. Another is a subclass throwing UnsupportedOperationException for a parent method. The fix is a better hierarchy or composition.
25

A batch job inserting 1 lakh rows through JPA takes 30 minutes. How do you speed it up?

Save to ▾
Show answer
Enable JDBC batching with hibernate.jdbc.batch_size around 50 and order_inserts, and avoid IDENTITY id generation, which disables insert batching; use a SEQUENCE with a pooled optimizer. Flush and clear the EntityManager every batch so the persistence context does not grow. For very large loads use JdbcTemplate batchUpdate or the database bulk loader. This often cuts time to a minute or two.
26

Memory usage is high because millions of Integer objects are stored in an ArrayList. What would you do?

Save to ▾
Show answer
Each Integer is a separate object with header overhead and a reference, so a List of Integer uses several times more memory than the raw data. If size is known, use an int[] array. Otherwise use primitive collections from libraries such as Eclipse Collections or fastutil, which store ints directly. This also improves cache performance and reduces GC pressure.
27

Flatten a list of lists of integers and compute the sum of squares of the even numbers.

Save to ▾
Show answer
flatMap then use a primitive stream to avoid boxing. int result = lists.stream() .flatMap(List::stream) .filter(n -> n % 2 == 0) .mapToInt(n -> n * n) .sum(); mapToInt returns an IntStream, whose sum() is simpler and faster than reduce on boxed Integers.
28

Legacy code uses anonymous classes and loops everywhere. How would you modernise it safely?

Save to ▾
Show answer
First add tests around the behaviour. Then refactor in small steps: anonymous Comparators and Runnables become lambdas, simple loops that filter and transform become streams, and null checks around returns become Optional where useful. Keep complex loops with early exits as loops if a stream is less readable. Use IDE refactorings and review each change to avoid altering behaviour.
29

A downstream payment service is slow and your API threads pile up. How do you protect your service?

Save to ▾
Show answer
Set strict connect and read timeouts on the HTTP client. Add a Resilience4j circuit breaker so calls fail fast once the error rate crosses a threshold, a bulkhead to limit concurrent calls and retry with backoff only for safe idempotent requests. Return a clear fallback such as payment pending. Monitor breaker state through Actuator metrics and alerts.
30

What is exception chaining?

Save to ▾
Show answer
Exception chaining wraps a low level exception in a higher level one while keeping the original as the cause, for example throw new OrderException("save failed", sqlEx). The full stack trace shows both, with Caused by lines. It lets each layer speak its own language without losing the root cause, which is essential when debugging production logs.
31

Two scheduled jobs on different servers process the same records twice. How do you prevent this?

Save to ▾
Show answer
In-JVM locks do not work across servers. Use a distributed lock such as ShedLock with a database table or Redis, so only one instance runs the job at a time. Make the processing idempotent too, for example by marking records with a status and updating with WHERE status = 'NEW' so only one worker claims each row. Database SELECT FOR UPDATE SKIP LOCKED also works well.
32

What is a deadlock and how can it be prevented?

Save to ▾
Show answer
A deadlock happens when two or more threads each hold a lock and wait for a lock held by the other, so none can continue. It needs mutual exclusion, hold and wait, no preemption and circular wait. Prevent it by always acquiring locks in the same global order, using tryLock with a timeout, holding locks briefly and avoiding calls to unknown code while holding a lock.
33

Is it good practice to catch Exception or Throwable?

Save to ▾
Show answer
Usually no. Catching Throwable also catches Errors like OutOfMemoryError that the app cannot recover from, and catching Exception hides bugs by treating all failures the same. Catch the most specific exceptions you can handle. A broad catch is acceptable only at a top boundary, such as a global handler or thread entry point, where you log and return a safe error.
34

Describe a time you had to learn a new technology quickly.

Save to ▾
Show answer
Situation: I joined a project using reactive Spring WebFlux with no prior experience. Task: contribute within two weeks. Action: I studied Project Reactor basics, built a small practice service, paired with a senior on my first ticket and kept notes on common operators. Result: I delivered my first feature in the second week and later wrote the team guide on avoiding blocking calls in reactive code.
35

Add optimistic locking to an entity and handle the conflict.

Save to ▾
Show answer
Add a version field; Hibernate checks it on update. @Entity class Account { @Id Long id; long balance; @Version Long version; } @Retryable(retryFor = ObjectOptimisticLockingFailureException.class, maxAttempts = 3) @Transactional public void debit(Long id, long amt) { Account a = repo.findById(id).orElseThrow(); a.balance -= amt; } The update includes WHERE version = ?, so a stale write fails and is retried.
36

What is the first level and second level cache in Hibernate?

Save to ▾
Show answer
The first level cache is the persistence context itself; it is per session or EntityManager, always on, and returns the same object for repeated finds by id in one transaction. The second level cache is shared across sessions and optional, backed by providers like Ehcache or Infinispan through JCache. Use it for read-mostly reference data, and be careful about stale data in clustered setups.
37

An order must update inventory and payment in different services. How do you keep data consistent?

Save to ▾
Show answer
Distributed two-phase commit is fragile, so use the saga pattern. Each service performs a local transaction and publishes an event; failures trigger compensating actions, such as releasing stock when payment fails. Use the transactional outbox pattern so the database change and event publish never diverge, and make consumers idempotent because Kafka may deliver a message more than once.
38

How does JWT based authentication work in a Spring Boot API?

Save to ▾
Show answer
After login, the auth server issues a signed JWT with claims like user id, roles and expiry. The client sends it in the Authorization: Bearer header. The API, configured as an OAuth2 resource server in Spring Security, verifies the signature with the public key, checks expiry and builds the security context, so no session is needed. Keep tokens short-lived and use refresh tokens for renewal.
39

A deep inheritance hierarchy of six levels is hard to change. How would you refactor it?

Save to ▾
Show answer
I would identify which behaviours actually vary and pull them into small interfaces, then replace inheritance with composition where a class holds strategy objects. Shared helper code can move to separate components. I would refactor step by step behind existing tests, starting from the leaves, so behaviour stays the same. The result is flatter classes that are easier to test and extend.
40

Write a JPQL query that returns a DTO projection instead of entities.

Save to ▾
Show answer
Projections load only needed columns and avoid dirty checking. public record OrderSummary(Long id, String customer, long total) {} @Query(""" select new com.shop.OrderSummary(o.id, c.name, o.total) from Order o join o.customer c where o.createdAt >= :from """) List<OrderSummary> summaries(@Param("from") LocalDate from); Interface-based projections in Spring Data are another option.

Frequently asked questions

What is asked in Java interviews for 7 years of experience?

Seven year engineers are expected to act as tech leads or principal engineers. Interviews focus on architecture of systems you owned, migration from monolith to microservices, observability, security, cost and team practices. You should explain how you made decisions with trade-offs, guided other engineers and improved delivery quality across services.

How many questions should I practise before a Java interview?

Work through all 40 questions here, then the company-wise sets for the employers you are targeting. Quality matters more than count: be able to explain why each answer is right.

Which topics matter most for 7 years of experience?

Focus first on Architecture and migrations, Observability and reliability, Security and compliance, Team leadership.