40 questions with answers for candidates with 1 year of experience — 15 easy, 24 medium, 1 hard.
What interviewers expect: 1 year experience
With one year of experience, interviewers expect solid core Java plus hands-on Spring Boot work: building REST APIs, using JPA repositories, writing unit tests and debugging issues. Expect questions on HashMap internals, exception handling in APIs, Java 8 streams and your current project's flow. Coding rounds stay at easy to medium level with collections based problems.
This set is weighted towards Java 8+ Features and Streams (9), Java Basics and JVM (8), Collections Framework (6), OOP in Java (5).
Spring Boot REST APIs Java 8 streams HashMap and collections internals JUnit and Mockito
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.
Fail-fast iterators, used by ArrayList and HashMap, throw ConcurrentModificationException if the collection is structurally modified during iteration other than through the iterator itself; they check a modCount. Fail-safe or weakly consistent iterators, as in ConcurrentHashMap and CopyOnWriteArrayList, work on a snapshot or tolerate changes and never throw, but may not show the latest updates.
02
A query is fast in development but takes 8 seconds in production. How do you investigate?
Production has more data, so check the execution plan with EXPLAIN ANALYZE on production-like data. Look for full table scans, missing indexes on filter or join columns, functions on indexed columns and poor statistics. Check if Hibernate generates the SQL you expect. Add a suitable composite index, rewrite the query or paginate, and verify the plan improves before release.
03
Legacy code uses anonymous classes and loops everywhere. How would you modernise it safely?
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.
04
A stream pipeline that updates a shared ArrayList in forEach gives random results with parallel(). Why?
ArrayList is not thread safe, and parallel streams run forEach on many threads, so additions race, get lost or throw exceptions. Side effects in streams are the problem. Replace forEach with collect(Collectors.toList()) or toList(), which handles merging per thread safely. Keep lambdas stateless and avoid modifying external state inside stream operations.
05
Write Java code to reverse an integer without converting it to a string.
Take the last digit with % 10 and build the result, checking for overflow.
public static int reverse(int x) {
long rev = 0;
while (x != 0) {
rev = rev * 10 + x % 10;
x /= 10;
}
if (rev > Integer.MAX_VALUE || rev < Integer.MIN_VALUE) return 0;
return (int) rev;
}
Negative numbers work because % keeps the sign in Java.
06
What are the primitive data types in Java and their sizes?
Java has eight primitives: byte (1 byte), short (2), int (4), long (8), float (4), double (8), char (2 bytes, UTF-16 code unit) and boolean (true or false, size JVM dependent). Primitives store values directly and have default values when used as fields, for example 0 for int and false for boolean. Each has a wrapper class such as Integer.
07
An application gets StackOverflowError in a recursive method. What do you do?
StackOverflowError means the thread stack is full, usually because recursion has no proper base case or the input is very deep. First check the base case and the recursive step with the failing input. If recursion is correct but deep, such as walking a long linked structure, convert it to an iterative solution with an explicit stack. Raising -Xss is only a temporary workaround.
The JVM first interprets bytecode, then profiles which methods run often. The Just In Time compiler converts these hot methods into optimised native code at runtime. HotSpot uses tiered compilation: C1 compiles quickly with light optimisation and C2 applies aggressive optimisations like inlining and escape analysis. This is why Java apps get faster after a warm-up period.
09
Tell me about a time you made a codebase more readable.
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.
10
Describe a time you improved the design of existing code.
Situation: our notification module used a 400 line class with switch cases for email, SMS and WhatsApp. Task: add push notifications without breaking anything. Action: I wrote tests for current behaviour, extracted a Notifier interface with one class per channel and used Spring to inject them by type. Result: push was added in one new class, bugs in that module dropped and new channels now take hours, not days.
11
What is Spring Boot and how is it different from the Spring Framework?
Spring Framework provides dependency injection, MVC, transactions and data access but needs manual configuration. Spring Boot builds on it with auto-configuration, starter dependencies, an embedded server such as Tomcat and production features through Actuator, so you can run a service with java -jar. Spring Boot 3 requires Java 17 or later and uses Jakarta EE packages instead of javax.
12
A counter shared between threads shows wrong totals. How do you fix it?
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.
13
What is the difference between wait() and sleep()?
wait() is an Object method called inside synchronized code; it releases the monitor and waits until notify(), notifyAll() or a timeout. sleep() is a Thread static method that pauses the current thread for a time but keeps any locks it holds. wait() is for coordination between threads, while sleep() simply delays. Modern code prefers Condition, BlockingQueue or CountDownLatch.
14
Users get LazyInitializationException when the API returns an entity. What is happening?
The entity was loaded inside a transaction, the session closed, and then Jackson touched a lazy association outside it. Do not fix it by turning on open-session-in-view or making everything eager. Instead, map the entity to a DTO inside the service transaction and fetch needed associations explicitly with JOIN FETCH or an entity graph. Spring Boot logs a warning because open-in-view is on by default.
15
What is the difference between HashMap, LinkedHashMap and TreeMap?
HashMap gives O(1) average operations with no ordering guarantee. LinkedHashMap keeps insertion order, or access order if configured, which helps build an LRU cache. TreeMap keeps keys sorted by natural order or a Comparator with O(log n) operations and supports range methods like floorKey and headMap. HashMap allows one null key; TreeMap does not allow null keys with natural ordering.
Single Responsibility: a class has one reason to change. Open/Closed: open for extension, closed for modification. Liskov Substitution: subclasses must work wherever the parent is expected. Interface Segregation: prefer small, focused interfaces. Dependency Inversion: depend on abstractions, not concrete classes. Spring dependency injection is a practical example of dependency inversion.
17
A HashMap shared by many threads sometimes loses updates. How do you fix it?
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.
18
Implement equals() and hashCode() for an Employee class with id and email.
Use the same fields in both methods.
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Employee e)) return false;
return id == e.id && Objects.equals(email, e.email);
}
@Override
public int hashCode() {
return Objects.hash(id, email);
}
Pattern matching for instanceof (Java 16) avoids an explicit cast.
19
What is the difference between an abstract class and an interface in modern Java?
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.
finally runs after try and catch in almost every case, including when the try block returns or throws. It does not run if the JVM exits through System.exit(), the process is killed or the thread dies abruptly. Avoid returning from finally, because that silently overrides the try block's return value and swallows exceptions.
21
Write a simple REST controller in Spring Boot for creating and fetching products.
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.
23
Code builds a large CSV report with String += inside a loop and it is very slow. Why and what is the fix?
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.
24
You have to process tasks in order of priority. Which collection do you use?
Use PriorityQueue, a binary heap where poll() always returns the smallest element by natural order or by a Comparator, such as Comparator.comparingInt(Task::priority). Insert and poll are O(log n) and peek is O(1). For multiple threads use PriorityBlockingQueue. Iterating a PriorityQueue does not give sorted order; only repeated poll() does.
25
What is the difference between map() and flatMap()?
map() transforms each element into exactly one new element, so a Stream of orders mapped to totals stays one-to-one. flatMap() transforms each element into a stream and flattens all of them into one stream, which is useful for one-to-many cases, such as turning a list of orders into a single stream of all items with orders.stream().flatMap(o -> o.items().stream()).
26
You need a cache that evicts the least recently used item when full. How would you build it in Java?
Extend LinkedHashMap with accessOrder set to true and override removeEldestEntry to return true when size exceeds capacity. Each get moves the entry to the end, so the eldest is the least recently used. It is not thread safe, so wrap it with synchronization for shared use. In production prefer Caffeine, which offers size and time based eviction with high concurrency.
27
You need to remove items from an ArrayList while looping over it. How do you do it safely?
Removing inside a for-each loop throws ConcurrentModificationException. Use list.removeIf(item -> item.isExpired()), which is clear and efficient. Alternatives are an explicit Iterator calling iterator.remove(), or looping backwards by index. For large lists removeIf is best because it shifts elements once instead of on every removal.
Autoboxing is automatic conversion between a primitive and its wrapper, such as int to Integer, and unboxing is the reverse. A common pitfall is a NullPointerException when unboxing a null Integer. Another is comparing Integer objects with ==, which works only for cached values from -128 to 127. Boxing inside tight loops also creates extra garbage and slows code.
Situation: our team was still on Java 8 while LTS releases moved ahead. Task: make a case for upgrading. Action: I followed release notes and JEPs, tried records, pattern matching and virtual threads in a side project, and built a proof of concept moving one service to Java 21 with measured gains. Result: the team approved the upgrade and I ran an internal session on the new features.
30
What are virtual threads and when should you use them?
Virtual threads, final in Java 21, are lightweight threads managed by the JVM and mounted on a small pool of carrier OS threads. When one blocks on I/O, it unmounts so the carrier can run another. You can run millions of them, which suits thread-per-request servers doing lots of blocking calls. They do not speed up CPU-bound work, and you should not pool them.
31
What are records in Java and when should you use them?
Records, final in Java 16, are concise classes for immutable data. record Point(int x, int y) {} generates private final fields, a canonical constructor, accessors, equals(), hashCode() and toString(). You can add validation in a compact constructor and add methods. Use them for DTOs, API responses and map keys. They cannot extend another class and are not suited to JPA entities, which need mutability.
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.
33
Write a sealed interface with records and a switch that computes area.
The switch needs no default because the type set is closed.
sealed interface Shape permits Circle, Rect {}
record Circle(double r) implements Shape {}
record Rect(double w, double h) implements Shape {}
static double area(Shape s) {
return switch (s) {
case Circle c -> Math.PI * c.r() * c.r();
case Rect(double w, double h) -> w * h;
};
}
The JVM runs bytecode and handles memory, garbage collection and JIT compilation. The JRE used to be the JVM plus core libraries needed to run programs. The JDK adds development tools such as javac, jar, javadoc and jshell. Since Java 11, vendors ship only the JDK, and jlink can build a slim custom runtime for deployment.
javac compiles source code into bytecode, not native machine code. Any machine with a compatible JVM can run that same .class file, so the code is written once and run anywhere. The JVM itself is platform specific; there are separate JVM builds for Windows, Linux and macOS, but the bytecode they run is identical.
36
How do you handle feedback that your code is too clever?
Situation: a reviewer said my one-line stream with nested collectors was hard to follow. Task: balance brevity with clarity. Action: I accepted the point, split the pipeline into named steps with small helper methods and added a comment on the business rule. Result: the next person who changed it did so without asking me, and I now aim for code a new joiner can read in one go.
Method references are short forms of lambdas that just call an existing method. Types: static method (Integer::parseInt), instance method of a specific object (System.out::println), instance method of an arbitrary object of a type (String::toUpperCase) and constructor (ArrayList::new). They make stream code clearer when the lambda only forwards its arguments.
38
What is the difference between reduce() and collect()?
reduce() combines elements into a single immutable value using an identity and an associative function, such as summing numbers. collect() is a mutable reduction that accumulates into a container like a List, Map or StringBuilder, which is far more efficient for building collections. Using reduce to build a list creates many intermediate copies, so use collect for containers.
String is immutable and thread safe by design. StringBuilder is mutable and not synchronized, so it is the fastest choice for building strings in a single thread, such as in loops. StringBuffer is mutable and synchronized, so it is thread safe but slower, and is rarely needed today. The compiler already optimises simple + concatenation outside loops.
40
Write a Java program to check whether a number is prime.
Check divisibility only up to the square root, which makes it O(sqrt n).
public static boolean isPrime(int n) {
if (n < 2) return false;
if (n % 2 == 0) return n == 2;
for (int i = 3; (long) i * i <= n; i += 2) {
if (n % i == 0) return false;
}
return true;
}
The long cast avoids overflow for large n.
Frequently asked questions
What is asked in Java interviews for 1 year of experience?
With one year of experience, interviewers expect solid core Java plus hands-on Spring Boot work: building REST APIs, using JPA repositories, writing unit tests and debugging issues. Expect questions on HashMap internals, exception handling in APIs, Java 8 streams and your current project's flow. Coding rounds stay at easy to medium level with collections based problems.
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 1 year of experience?
Focus first on Spring Boot REST APIs, Java 8 streams, HashMap and collections internals, JUnit and Mockito.