Skip to content

Java Mock Interview: 20 Questions in 50 Minutes

Four rounds that copy a real interview. Answer aloud, then check the model answers.

Mock interview format

  1. Warm-up · 5 minutes — 4 questions
  2. Technical · 20 minutes — 7 questions
  3. Scenario · 15 minutes — 5 questions
  4. HR & behavioural · 10 minutes — 4 questions

Tip: record yourself and listen back. Most people talk too fast and skip the key idea.

Mock progressStart 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

What is the difference between intermediate and terminal operations in streams?

Save to ▾
Show answer
Intermediate operations like filter, map, sorted and distinct return a new stream and are lazy; nothing runs until a terminal operation is called. Terminal operations like collect, forEach, reduce, count and findFirst trigger processing and produce a result. Laziness lets streams fuse steps into a single pass and short-circuit, so findFirst on filtered data stops early.
02

What does the var keyword do and where can it not be used?

Save to ▾
Show answer
var, added in Java 10, lets the compiler infer the type of a local variable from its initializer, for example var list = new ArrayList<String>(). Java stays statically typed. var cannot be used for fields, method parameters or return types, and it needs an initializer that is not null. Use it when the type is obvious to keep code readable.
03

Why is PreparedStatement preferred over Statement?

Save to ▾
Show answer
PreparedStatement sends the SQL with placeholders separately from the parameter values, so user input is never treated as SQL, which prevents SQL injection. The database can also cache and reuse the execution plan, and it handles types like dates correctly. Statement with string concatenation is unsafe and slower for repeated queries, so it should not be used with user input.
04

What is the difference between checked and unchecked exceptions?

Save to ▾
Show answer
Checked exceptions extend Exception (but not RuntimeException) and must be caught or declared with throws, for example IOException and SQLException. Unchecked exceptions extend RuntimeException, such as NullPointerException and IllegalArgumentException, and need no declaration. Use checked exceptions for recoverable conditions callers must handle and unchecked ones for programming errors. Errors like OutOfMemoryError should not be caught.
05

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.
06

Explain the entity lifecycle states in JPA.

Save to ▾
Show answer
Transient: a new object not yet linked to a persistence context. Managed (persistent): attached to the context, so changes are tracked and flushed automatically through dirty checking. Detached: was managed but the context closed or it was evicted; changes are not tracked until merge(). Removed: scheduled for deletion on flush. persist, merge, detach and remove move entities between these states.
07

Write a record with validation in its compact constructor.

TechnicalOOP in JavaMedium
Save to ▾
Show answer
A compact constructor runs before fields are assigned. public record Money(String currency, long paise) { public Money { Objects.requireNonNull(currency); if (paise < 0) { throw new IllegalArgumentException("negative amount"); } } public Money add(Money o) { return new Money(currency, paise + o.paise); } } Storing money in paise as long avoids floating point errors.
08

What is the difference between an abstract class and an interface in modern Java?

TechnicalOOP in JavaMedium
Save to ▾
Show answer
An abstract class can have state (instance fields), constructors and any access modifier, and a class can extend only one. An interface has no instance state but, since Java 8, can have default and static methods, and since Java 9 private methods; a class can implement many. Use an interface for a capability contract and an abstract class to share code and state among closely related classes.
09

What is the difference between lazy and eager loading?

Save to ▾
Show answer
Lazy loading fetches an association only when it is first accessed, using a proxy; eager loading fetches it immediately with the parent. In JPA, @ManyToOne and @OneToOne default to EAGER, while @OneToMany and @ManyToMany default to LAZY. Best practice is to make all associations lazy and fetch what each use case needs with JOIN FETCH or entity graphs, which avoids loading huge object graphs.
10

What is Optional and how should it be used?

Save to ▾
Show answer
Optional is a container that may or may not hold a value, used mainly as a method return type to show that a result can be absent, for example findById. Use map, filter, orElse, orElseGet and orElseThrow instead of calling get() blindly. Do not use Optional for fields, parameters or collections, and prefer orElseGet when the default is costly to create.
11

Using streams, find the employee with the highest salary in each department.

Save to ▾
Show answer
Group by department with a maxBy downstream collector. Map<String, Optional<Employee>> top = employees.stream() .collect(Collectors.groupingBy( Employee::department, Collectors.maxBy(Comparator.comparingInt(Employee::salary)))); To get values without Optional, wrap with collectingAndThen(maxBy(...), Optional::get), which is safe because each group has at least one element.
12

Code builds a large CSV report with String += inside a loop and it is very slow. Why and what is the fix?

Save to ▾
Show answer
Each += creates a new String and copies all previous characters, so building n rows is O(n squared) in time and creates huge garbage. Use a single StringBuilder with append() inside the loop, ideally with an initial capacity, or write rows directly to a BufferedWriter for very large output. This turns minutes of work into milliseconds.
13

A file handle leak causes Too many open files errors after a day. What is the likely cause?

Save to ▾
Show answer
Streams, readers or connections are opened but not closed on all paths, especially when an exception is thrown before close(). Check with lsof or jcmd which files are open. Fix by wrapping every resource in try-with-resources so it always closes, and make sure Files.lines() and Files.list() streams are closed too, since they hold file handles.
14

A getter returns an internal List and callers modify it, causing bugs. How do you fix this?

ScenarioOOP in JavaMedium
Save to ▾
Show answer
This breaks encapsulation. Return an unmodifiable view with Collections.unmodifiableList(list) or a copy with List.copyOf(list), so callers cannot change internal state. Also copy the list passed into the constructor or setter. If the class should be fully immutable, store List.copyOf in a final field. Expose specific methods like addItem() when controlled changes are needed.
15

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.
16

A counter shared between threads shows wrong totals. How do you fix it?

Save to ▾
Show answer
count++ is not atomic; two threads can read the same value and both write the same result, so updates are lost. Use AtomicInteger.incrementAndGet(), which uses CAS, or LongAdder for very high contention, as it spreads updates over cells. A synchronized method also works but is slower. volatile alone does not fix it because it gives visibility, not atomicity.
17

How do you explain OOP concepts to a junior developer who is new to Java?

HR & behaviouralOOP in JavaEasy
Save to ▾
Show answer
Situation: I mentored two interns who struggled with OOP. Task: help them design classes for a library app. Action: I used real objects they knew, like Book and Member, showed encapsulation with private fields, then wrote one interface with two implementations to show polymorphism, and reviewed their code daily. Result: within two weeks they designed modules on their own and their pull requests needed fewer review comments.
18

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

HR & behaviouralCollections FrameworkMedium
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.
19

Tell me about a time you made a codebase more readable.

HR & behaviouralJava 8+ Features and StreamsMedium
Save to ▾
Show answer
Situation: our reporting module had nested loops 200 lines long that new joiners feared. Task: make it maintainable without changing output. Action: I added snapshot tests on real report files, then refactored into small methods using streams, groupingBy and records for intermediate data, and reviewed each step with a teammate. Result: the module shrank by 40 percent and later changes took a day instead of a week.
20

Describe a situation where you had to deliver under a tight deadline.

HR & behaviouralMultithreading and ConcurrencyMedium
Save to ▾
Show answer
Situation: a bulk upload feature had to go live in four days for a client launch. Task: build it safely in time. Action: I split it into must-have and later items, used an ExecutorService to process rows in parallel, wrote focused tests for validation and kept the product owner updated daily. Result: we shipped on time, it handled 50,000 rows in under two minutes and we added the extras next sprint.

Frequently asked questions

How do I use this mock interview?

Set a 50-minute timer, answer every question aloud (or ask a friend to read them), and open answers only after each round. Note every question where your answer missed the key idea.

How often should I take a mock?

Once a week while preparing and once two or three days before a real interview. The question order is fixed, so for fresh practice use the company and experience pages too.