Java interview questions for live coding
Here are 11 practical Java interview questions you can paste into a shared editor, from warm-up to senior. Each has starter code that has been run, what a good answer shows, and one follow-up. They test working Java: collections, records, streams and concurrency.
Try it in a pad2 free interviews, no card needed.
How to use these
Pick one warm-up and one core or senior question for a 45 minute interview. Paste the code block into a pad before the candidate joins. The lines marked // => show what a correct answer prints, so the candidate can run the file and check their own work.
Some questions are a function to write. Others are working code with a bug, because reading code is most of the job. For how to choose and pace a question, see our guide to technical interview questions.
The questions
1. Count the words Warm-up
Return how many times each word appears in a text. Words are separated by spaces and case does not matter.
import java.util.*; class Main { static Map<String, Integer> count(String text) { return new TreeMap<>(); } public static void main(String[] args) { System.out.println(count("To be or not to be")); // => {be=2, not=1, or=1, to=2} System.out.println(count("")); // => {} } }A good answer shows: Map.merge or getOrDefault, and a split that copes with the empty string. Ask why the output is sorted: they should spot the TreeMap.
Follow-up: Print the words by count, highest first.
2. The point that is not in the set Warm-up
This prints false. Ask the candidate to explain why and to fix it.
import java.util.*; class Main { static class Point { final int x, y; Point(int x, int y) { this.x = x; this.y = y; } } public static void main(String[] args) { Set<Point> seen = new HashSet<>(); seen.add(new Point(1, 2)); System.out.println(seen.contains(new Point(1, 2))); // => false } }A good answer shows: They know a HashSet uses hashCode and then equals, and that both must be overridden together. Turning Point into a record is the shortest fix.
Follow-up: What goes wrong if a field used in hashCode changes while the object is in the set?
3. One page of a list Warm-up
Return page number page (starting at 1) of a list, with size items per page. A page past the end is an empty list, not an exception.
import java.util.*; class Main { static <T> List<T> page(List<T> items, int page, int size) { return List.of(); } public static void main(String[] args) { List<Integer> items = List.of(1, 2, 3, 4, 5, 6, 7); System.out.println(page(items, 2, 3)); // => [4, 5, 6] System.out.println(page(items, 3, 3)); // => [7] System.out.println(page(items, 4, 3)); // => [] } }A good answer shows: Careful index arithmetic with Math.min, and a view on what page 0 or size 0 should do. Good candidates ask before they guess.
Follow-up: subList returns a view. When would that surprise the caller?
4. Parse a duration Core
Parse strings such as "1h30m15s" into seconds. Each unit is optional but the order is fixed. Anything else throws IllegalArgumentException.
class Main { static long seconds(String text) { return 0; } public static void main(String[] args) { System.out.println(seconds("1h30m15s")); // => 5415 System.out.println(seconds("45s")); // => 45 System.out.println(seconds("2h")); // => 7200 try { seconds("15s1h"); System.out.println("no exception"); } catch (IllegalArgumentException e) { System.out.println("rejected"); // => rejected } } }A good answer shows: A regex with optional groups or a small hand-written scanner, and a decision about the empty string. Either approach is fine if they can defend it.
Follow-up: Product now wants "1.5h" and "90 min". How much of your code survives?
5. Remove while iterating Core
This code is meant to remove the even numbers. It throws. Ask the candidate to explain the exception and give two fixes.
import java.util.*; class Main { public static void main(String[] args) { List<Integer> numbers = new ArrayList<>(List.of(1, 2, 3, 4, 5, 6)); try { for (Integer n : numbers) { if (n % 2 == 0) numbers.remove(n); } System.out.println(numbers); } catch (RuntimeException e) { System.out.println(e.getClass().getSimpleName()); // => ConcurrentModificationException } } }A good answer shows: They know the for-each loop uses an iterator that checks for changes. removeIf, an explicit Iterator.remove, or a new filtered list all work.
Follow-up: Change Integer n to int n. What does numbers.remove(n) do now?
6. Totals per customer with streams Core
Given a list of orders, return each customer with their total amount, largest total first.
import java.util.*; import java.util.stream.*; class Main { record Order(String customer, int amount) {} static List<Map.Entry<String, Integer>> totals(List<Order> orders) { return List.of(); } public static void main(String[] args) { List<Order> orders = List.of(new Order("ana", 30), new Order("bo", 15), new Order("ana", 12)); System.out.println(totals(orders)); // => [ana=42, bo=15] } }A good answer shows: Collectors.groupingBy with summingInt, then a sort on the entries. A plain loop with a HashMap is also a good answer, and often clearer.
Follow-up: Which version would you rather review in a pull request, and why?
7. Sort by three things Core
Sort employees by department A to Z, then by salary highest first, then by name A to Z.
import java.util.*; class Main { record Employee(String name, String dept, int salary) {} static List<String> sortedNames(List<Employee> staff) { return staff.stream().map(Employee::name).toList(); } public static void main(String[] args) { List<Employee> staff = List.of( new Employee("Cy", "ops", 50), new Employee("Ana", "eng", 70), new Employee("Bo", "eng", 90), new Employee("Al", "eng", 70)); System.out.println(sortedNames(staff)); // => [Bo, Al, Ana, Cy] } }A good answer shows: Comparator.comparing with thenComparing, and the reversed() trap: reversing the whole chain also reverses the department order.
Follow-up: Department can be null. Where should those people go, and how do you say so in the comparator?
8. Money that adds up Core
Design a small Money type. It can be created from a string such as "19.99", added to another Money of the same currency, and printed. Adding different currencies throws.
class Main { record Money(long cents, String currency) { static Money of(String amount, String currency) { return new Money(0, currency); } Money add(Money other) { return this; } } public static void main(String[] args) { System.out.println(0.1 + 0.2); // => 0.30000000000000004 Money total = Money.of("19.99", "USD").add(Money.of("0.01", "USD")); System.out.println(total); // => 20.00 USD } }A good answer shows: They can say why double is wrong for money, pick long cents or BigDecimal, and override toString. Immutability should come for free with the record.
Follow-up: Split 10.00 USD three ways. Where does the last cent go?
9. A cache whose entries expire Senior
Build a cache where each entry has a time to live in milliseconds. get returns null once the entry has expired. The clock is passed in so the test controls time.
import java.util.*; import java.util.function.LongSupplier; class Main { static class TtlCache<K, V> { TtlCache(LongSupplier clock) {} void put(K key, V value, long ttlMillis) {} V get(K key) { return null; } } public static void main(String[] args) { long[] now = {0}; TtlCache<String, Integer> cache = new TtlCache<>(() -> now[0]); cache.put("a", 1, 100); now[0] = 99; System.out.println(cache.get("a")); // => 1 now[0] = 100; System.out.println(cache.get("a")); // => null } }A good answer shows: They store the expiry time beside the value and check it on read. Strong candidates raise the entries nobody reads again before you ask.
Follow-up: Add that cleanup. Then make the class safe for many threads.
10. The counter that loses updates Senior
Four threads each add 1,000,000 to a counter. The total should be 4000000, and on many runs it is lower. Ask the candidate to explain and fix it.
class Main { static int count = 0; public static void main(String[] args) throws InterruptedException { Thread[] threads = new Thread[4]; for (int i = 0; i < threads.length; i++) { threads[i] = new Thread(() -> { for (int j = 0; j < 1_000_000; j++) count++; }); threads[i].start(); } for (Thread t : threads) t.join(); System.out.println(count); } }A good answer shows: They explain that count++ is read, add, write, and fix it with AtomicInteger, synchronized or LongAdder. They should also know volatile alone does not fix it.
Follow-up: Two fields must now change together. Which of your fixes still works?
11. Three slow calls at once Senior
slow() stands in for a remote call that takes 300 ms. Make total() add up three calls in about 300 ms, not 900 ms.
import java.util.*; import java.util.concurrent.*; class Main { static int slow(int x) { try { Thread.sleep(300); } catch (InterruptedException e) { throw new RuntimeException(e); } return x * 10; } static int total(List<Integer> inputs) { int sum = 0; for (int x : inputs) sum += slow(x); return sum; } public static void main(String[] args) { long start = System.nanoTime(); System.out.println(total(List.of(1, 2, 3))); // => 60 System.out.println("under 600 ms: " + ((System.nanoTime() - start) / 1_000_000 < 600)); } }A good answer shows: CompletableFuture.supplyAsync with an executor they create and shut down, or invokeAll. The last line should print true when they are done.
Follow-up: One call throws. What does the caller see, and what happens to the other two?
Run them with a candidate
Every snippet here is a single file with a class named Main and uses only the JDK. If you want a pad that both of you can type in and run, QuizzX is Java0/month per team for unlimited interviews, and the first 2 are free. See the online code editor for interviews page or the pricing.
Questions
- Which Java version do these questions need?
- Java 17 or newer. The snippets use records and Stream.toList, and nothing outside the JDK. Each one has been compiled and run.
- Why is every class called Main?
- So each snippet is one file that runs as pasted. In a QuizzX pad, keep the class name Main, as in the Java starter.
- Can I use these for a Spring or Android role?
- Yes, as a test of the language and the collections library. They do not test a framework.
- The counter question prints a different number on each run. Is that right?
- Yes. The bug is a race between threads, so the wrong total changes from run to run and is sometimes correct. That is part of what the candidate should explain.
Read next
- Python interview questions
- JavaScript interview questions
- Technical interview questions
- Online code editor for interviews
- Pricing
Try it in a pad2 free interviews, no card needed.