Skip to content
RED SAGSkills

Java interview questions and answers

Java interview questions test the language and the JVM: object-oriented design, collections, exceptions and concurrency, the things backend and Android teams use every day.

Below are 32 Java questions with the correct answer and a short explanation, grouped from fresher to experienced level. Try each one before you open the answer.

What Java interviews usually check

  • ✓OOP: classes, interfaces, inheritance and polymorphism
  • ✓Collections: List, Set, Map and their trade-offs
  • ✓Exceptions and resource handling
  • ✓Threads, executors and synchronisation
  • ✓Memory, garbage collection and the JVM

Java interview questions for freshers easy

1. Safe midpoint in binary search

In Java or C++, why is mid = lo + (hi - lo) / 2 preferred over (lo + hi) / 2?

  1. A.It rounds the midpoint up instead of down
  2. B.It makes the search return the first match
  3. C.lo + hi can overflow a 32-bit int for large indexes
  4. D.It avoids a division by zero when lo is 0
Show answer

Answer: C. lo + hi can overflow a 32-bit int for large indexes

If lo and hi are both above about 1.07 billion, lo + hi exceeds the int range and becomes negative. hi - lo never overflows when both are valid indexes. This exact bug sat in the JDK binary search for years.

2. null keys in Java maps

Which Java map allows a single null key?

  1. A.Hashtable
  2. B.HashMap
  3. C.ConcurrentHashMap
  4. D.None of them
Show answer

Answer: B. HashMap

HashMap allows one null key and many null values. Hashtable and ConcurrentHashMap reject null keys and values with a NullPointerException, partly because null would make get ambiguous under concurrency.

3. What HashMap.put returns

In Java, what does map.put("UAE", 5) return if "UAE" already mapped to 3?

  1. A.5
  2. B.true
  3. C.null
  4. D.3
Show answer

Answer: D. 3

put returns the previous value for the key, or null if there was none (or it was null). It replaces the old value. Use putIfAbsent when you do not want to overwrite.

4. Overflow-safe midpoint formula

In Java or C++, with int indices, which midpoint formula avoids integer overflow when lo and hi are both large?

  1. A.mid = (lo + hi) / 2
  2. B.mid = (lo * hi) / 2
  3. C.mid = lo + (hi - lo) / 2
  4. D.mid = hi / 2 + lo
Show answer

Answer: C. mid = lo + (hi - lo) / 2

lo + hi can exceed the largest int (about 2.1 billion) and wrap to a negative number. hi - lo never overflows when both are valid indices, so lo + (hi - lo) / 2 is safe. This bug existed in the JDK's own binary search for years.

5. Default order of Java PriorityQueue

In Java, new PriorityQueue<Integer>() receives 5, 1 and 3. What does poll() return first?

  1. A.5
  2. B.1
  3. C.3
  4. D.The order of insertion, so 5
Show answer

Answer: B. 1

Java's PriorityQueue is a min-heap by natural ordering, so the smallest value comes out first. For a max-heap, pass Comparator.reverseOrder() or (a, b) -> b - a, though Integer.compare(b, a) avoids overflow.

6. Tracing with little code

A team wants traces from a Java service quickly without editing much code. What OpenTelemetry option helps?

  1. A.Writing a custom tracer from scratch
  2. B.Adding print statements to each method
  3. C.Exporting heap dumps every minute
  4. D.Auto-instrumentation via the Java agent
Show answer

Answer: D. Auto-instrumentation via the Java agent

OpenTelemetry offers automatic instrumentation for many languages, such as a Java agent, that captures spans for common frameworks like HTTP servers, clients and database drivers. You can add manual spans later for business steps.

7. Why include a warm-up

Why do many teams run a short warm-up period before the measured part of a test on a Java or .NET service?

  1. A.The load tool needs time to download the internet
  2. B.JIT compilation, caches and pools need time to reach normal state
  3. C.Warm-up makes the hardware physically faster
  4. D.It is needed so that HTTPS certificates are created
Show answer

Answer: B. JIT compilation, caches and pools need time to reach normal state

Right after start, code is still being compiled by the JIT, caches are empty and connection pools are being filled. Measurements in that window are slower than normal running. A warm-up lets you measure steady behaviour, while a separate test can study cold-start behaviour if it matters.

8. Accepting a browser alert in Selenium

A JavaScript alert appears after clicking "Submit". How do you accept it in Selenium (Java)?

  1. A.driver.findElement(By.id("alert")).click()
  2. B.driver.navigate().refresh()
  3. C.driver.switchTo().defaultContent()
  4. D.driver.switchTo().alert().accept()
Show answer

Answer: D. driver.switchTo().alert().accept()

Native alerts are not part of the DOM, so you cannot find them with locators. switchTo().alert() gives an Alert object with accept(), dismiss(), getText() and sendKeys() for prompts. Waiting with ExpectedConditions.alertIsPresent() first avoids timing errors.

9. Languages Playwright supports

Your company's teams use Java, Python and C#. Which statement about Playwright is correct?

  1. A.It has official libraries for JS/TS, Python, Java and .NET
  2. B.Playwright supports only JavaScript and TypeScript code
  3. C.Playwright supports Java only by running through Selenium Grid
  4. D.Playwright officially supports only Python and Ruby
Show answer

Answer: A. It has official libraries for JS/TS, Python, Java and .NET

Playwright is maintained for Node.js (JS/TS), Python, Java and .NET. The Playwright Test runner with fixtures, projects and the HTML report is Node-specific; other languages typically use their own test runners such as pytest, JUnit or NUnit.

10. Boolean search

You want Java developers who know Spring but not interns. Which search string is correct?

  1. A.Java OR Spring OR intern
  2. B.Java Spring intern
  3. C."Java" AND intern NOT Spring
  4. D.Java AND Spring NOT intern
Show answer

Answer: D. Java AND Spring NOT intern

AND requires both terms and NOT excludes a term, so "Java AND Spring NOT intern" finds profiles with both skills while removing interns. OR widens the search, and the other options include or require the wrong terms.

11. A searchable job title

A manager wants to post a role as "Code Ninja Rockstar". Why is "Backend Developer (Java)" better?

  1. A.Creative titles are banned on all job boards
  2. B.Standard titles mean the role pays more
  3. C.Search engines only show titles under three words
  4. D.Candidates search using standard titles, so it is found more
Show answer

Answer: D. Candidates search using standard titles, so it is found more

People search job boards for the titles they know. A clear, standard title with a key skill matches those searches and tells candidates exactly what the job is. Fun titles get fewer views and confuse applicants.

Java intermediate interview questions medium

12. Overriding equals without hashCode

A Java class Point overrides equals to compare x and y but does not override hashCode. What happens with a HashSet<Point>?

  1. A.Two equal points can both be added and contains often fails
  2. B.It works normally because HashSet only uses equals
  3. C.It fails to compile without a hashCode method
  4. D.All points land in one bucket and lookups slow down
Show answer

Answer: A. Two equal points can both be added and contains often fails

HashSet first uses hashCode to choose a bucket, then equals inside the bucket. The default hashCode is per object identity, so equal points usually go to different buckets and are never compared. Always override both, or use a Java record.

13. Changing a key after putting it in a set

In Java you add a mutable object to a HashSet, then change a field used by its hashCode. What happens next?

  1. A.The set rehashes it automatically
  2. B.contains and remove may fail to find it
  3. C.The set throws ConcurrentModificationException
  4. D.The object is copied, so nothing changes
Show answer

Answer: B. contains and remove may fail to find it

The entry stays in the bucket chosen by the old hash. Lookups now compute the new hash and search a different bucket, so the object is effectively lost while still taking space. Use immutable keys.

14. TreeMap or HashMap in Java

You need a Java map that can return all orders with timestamps between 10:00 and 11:00. Which fits and what does it cost?

  1. A.HashMap, with O(1) operations and range views
  2. B.HashMap, because it keeps keys sorted
  3. C.TreeMap, with O(log n) operations and range views
  4. D.TreeMap, with O(1) operations and no ordering
Show answer

Answer: C. TreeMap, with O(log n) operations and range views

TreeMap is a red-black tree that keeps keys sorted, so subMap(from, to) returns a range directly. Each operation is O(log n). HashMap is faster for exact lookups but has no key order, so ranges need a full scan.

15. Grouping into lists in Java

Which Java line adds order o to the list for its city, creating the list if needed?

  1. A.map.getOrDefault(city, new ArrayList<>()).add(o)
  2. B.map.put(city, List.of(o))
  3. C.map.computeIfAbsent(city, k -> new ArrayList<>()).add(o)
  4. D.map.putIfAbsent(city, new ArrayList<>()).add(o)
Show answer

Answer: C. map.computeIfAbsent(city, k -> new ArrayList<>()).add(o)

computeIfAbsent returns the existing list or creates, stores and returns a new one. getOrDefault returns a fresh list that is never stored, put with List.of replaces the list each time (and is immutable), and putIfAbsent returns null on first insert.

16. C-style integer division in JS

In C and Java, -7 / 2 with integers gives -3. Which JavaScript expression gives the same result?

  1. A.Math.floor(-7 / 2)
  2. B.-Math.ceil(7 / 2)
  3. C.Math.trunc(-7 / 2)
  4. D.Math.ceil(-7 / 2) - 1
Show answer

Answer: C. Math.trunc(-7 / 2)

C and Java integer division truncates towards zero, so -3.5 becomes -3. Math.trunc does the same for both signs. Math.floor rounds down to -4, which only matches truncation for positive numbers, and the other two options also give -4.

17. Too many open files error

A busy Java service starts failing with "Too many open files". What should you check first?

  1. A.Free disk space on the root filesystem
  2. B.The number of free inodes on /var
  3. C.The kernel version and installed patches
  4. D.Its open file limit and current fd count
Show answer

Answer: D. Its open file limit and current fd count

EMFILE means the process hit its per-process descriptor limit (RLIMIT_NOFILE). Compare "Max open files" in /proc/<pid>/limits with the count in /proc/<pid>/fd. Then raise the limit (for example LimitNOFILE in the systemd unit) and check for fd leaks.

18. SQL offline, Java online

The "avg_order_value_30d" feature is computed in SQL for training and re-written in Java for the online service. Values often differ slightly. What fixes the root cause?

  1. A.Round both values to the nearest rupee
  2. B.Retrain the model more often to absorb the gap
  3. C.Add a tolerance check on the model output
  4. D.Define the feature once and use it for both paths
Show answer

Answer: D. Define the feature once and use it for both paths

Two implementations drift apart through edge cases like nulls, windows and time zones. A single definition, served through a feature store or a shared library, removes this source of training-serving skew.

19. Mapping a response to a class

In REST Assured, how do you turn a JSON order response into an Order Java object?

  1. A....then().body(Order.class)
  2. B....then().extract().as(Order.class)
  3. C....when().cast(Order.class)
  4. D....given().as(Order.class)
Show answer

Answer: B. ...then().extract().as(Order.class)

extract().as(Order.class) deserialises the body using Jackson or Gson, if on the classpath. You can then use normal Java assertions on the fields. Unknown fields may need the mapper configured to ignore them.

20. What a thread dump reveals

Under load, a Java service stops responding but CPU is low. A thread dump shows 180 of 200 threads in BLOCKED state on the same monitor. What does that suggest?

  1. A.The CPU is simply too fast for this kind of workload
  2. B.Lock contention: many threads wait for one synchronized section
  3. C.The service is writing too few log files under load
  4. D.The network card has run out of bandwidth
Show answer

Answer: B. Lock contention: many threads wait for one synchronized section

BLOCKED threads are waiting to enter a synchronized block or method held by another thread. When most threads queue on the same lock, throughput collapses even with idle CPU. The stack traces show which code holds the lock, so it can be narrowed or removed.

21. An explicit wait in Selenium

What does this Selenium Java code do?

WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement pay = wait.until(
    ExpectedConditions.elementToBeClickable(By.cssSelector("[data-test=pay]")));
pay.click();
  1. A.Waits exactly 10 seconds, then clicks
  2. B.Clicks immediately and retries for 10 seconds
  3. C.Polls until the element is visible and enabled, up to 10 seconds, then clicks it; otherwise throws TimeoutException
  4. D.Sets an implicit wait of 10 seconds for all elements
Show answer

Answer: C. Polls until the element is visible and enabled, up to 10 seconds, then clicks it; otherwise throws TimeoutException

Explicit waits poll a condition and return as soon as it is true. Avoid mixing them with implicit waits, which can combine in surprising ways and make timeouts much longer than expected.

22. An unbracketed string

On an engine where AND is applied before OR, how is this string read?

Java OR Python AND Bangalore
  1. A.(Java OR Python) AND Bangalore
  2. B.Java AND Python AND Bangalore
  3. C.Only results that say 'Java OR Python'
  4. D.Java OR (Python AND Bangalore)
Show answer

Answer: D. Java OR (Python AND Bangalore)

With AND applied first, the engine pairs Python with Bangalore and then adds anyone who mentions Java anywhere. You get Java profiles from every city. Brackets, (Java OR Python) AND Bangalore, make the meaning clear on any engine.

Java interview questions for experienced candidates hard

23. Sharing a HashMap across threads

Several request threads in a Java service update one shared HashMap of counters. What is the right fix?

  1. A.Make the map variable volatile
  2. B.Use ConcurrentHashMap with merge or compute
  3. C.Use HashMap but read with getOrDefault
  4. D.Call map.size() before every update
Show answer

Answer: B. Use ConcurrentHashMap with merge or compute

Unsynchronized HashMap writes from several threads can lose updates or corrupt internal state. volatile only makes the reference visible, not the operations atomic. ConcurrentHashMap.merge(key, 1, Integer::sum) updates atomically per key.

24. int[] as a HashMap key

In Java, map.put(new int[]{1, 2}, "x") then map.get(new int[]{1, 2}) returns null. Why?

  1. A.Arrays use identity equals and hashCode
  2. B.int[] cannot be stored in a HashMap
  3. C.The array is copied and changed on insert
  4. D.HashMap sorts array keys first
Show answer

Answer: A. Arrays use identity equals and hashCode

Arrays do not override equals or hashCode, so two arrays with the same contents are different keys. Use List.of(1, 2), a record such as Point(int x, int y), or a String key.

25. A test that depends on HashMap order

A Java test compares map.toString() with an expected string. It breaks after more entries are added, though the contents are correct. What is the proper fix?

  1. A.Insert the keys in alphabetical order
  2. B.Use a fixed initial capacity of 16 entries
  3. C.Switch to Hashtable, which keeps a stable order
  4. D.Compare with equals, or use LinkedHashMap if order matters
Show answer

Answer: D. Compare with equals, or use LinkedHashMap if order matters

HashMap order depends on hash values and capacity, and a resize can reorder entries. Tests should compare contents with equals. If the output order is a real requirement, use LinkedHashMap for insertion order or TreeMap for sorted order.

26. Midpoint overflow in binary search

A Java binary search over a huge array uses `int mid = (lo + hi) / 2`. When can it fail, and what is the fix?

  1. A.lo + hi can overflow int; use lo + (hi - lo) / 2
  2. B.It fails for odd lengths; use (lo + hi + 1) / 2
  3. C.It fails for negatives; use Math.abs(lo + hi) / 2
  4. D.It never fails because Java widens ints
Show answer

Answer: A. lo + hi can overflow int; use lo + (hi - lo) / 2

If lo and hi are both above about 1.07 billion, lo + hi exceeds the int maximum and wraps to a negative number. lo + (hi - lo) / 2 gives the same midpoint without the large sum. This bug sat in the JDK's binary search for years.

27. Java Stack class or ArrayDeque

A Java code review flags new java.util.Stack<Integer>() in a hot path. What does the Java documentation recommend instead, and why?

  1. A.LinkedList, since Stack has O(n) push
  2. B.PriorityQueue, since Stack cannot hold Integers
  3. C.Nothing, Stack is the modern recommended class
  4. D.ArrayDeque, since Stack is a synchronized legacy Vector
Show answer

Answer: D. ArrayDeque, since Stack is a synchronized legacy Vector

Stack extends Vector, so every call takes a lock and it also exposes index methods that break the stack idea. The Deque interface, usually ArrayDeque, gives push, pop and peek without locking and is faster. For sharing between threads, use a concurrent deque instead.

28. Work-stealing deques in thread pools

In a work-stealing thread pool (like Java's ForkJoinPool), each worker has its own deque. How are the two ends used?

  1. A.All threads push and pop at the same end
  2. B.One shared deque is locked by every thread
  3. C.Workers steal only when their own deque is full
  4. D.Owner uses one end; thieves take the other
Show answer

Answer: D. Owner uses one end; thieves take the other

The owner pushes and pops its own tasks at one end (LIFO, cache-friendly). Idle workers steal from the opposite end, usually older and larger tasks, which keeps conflicts rare. This balances load without a central queue.

29. Java Pod OOMKilled with free heap

A Java service with a 2Gi memory limit and -XX:MaxRAMPercentage=90 is OOMKilled, yet heap graphs never pass 1.6Gi. Why?

  1. A.The JVM ignores container memory limits in every version, so it sizes for the host.
  2. B.Kubernetes counts heap memory twice when the kubelet compares the container usage with its memory limit.
  3. C.Heap is only part of JVM memory; metaspace, threads, code cache and buffers push it over.
  4. D.MaxRAMPercentage only takes effect on Windows containers, so the heap is unbounded here.
Show answer

Answer: C. Heap is only part of JVM memory; metaspace, threads, code cache and buffers push it over.

Modern JVMs read the cgroup limit, and MaxRAMPercentage sets only the maximum heap. Off-heap memory, such as threads, metaspace, Netty direct buffers and JIT code, also counts toward the container limit. Leaving 90 percent to heap leaves too little room. Native memory tracking helps measure the non-heap part.

30. Answering "are we affected?" fast

A critical zero-day like Log4Shell is announced in a common Java library. Leadership asks which of your 400 services are affected by tonight. What makes this a quick query rather than weeks of digging?

  1. A.Asking each team lead to reply by email tonight
  2. B.The latest yearly penetration test report
  3. C.SBOMs for every build stored in a searchable inventory
  4. D.Running SAST on every repository again tonight
Show answer

Answer: C. SBOMs for every build stored in a searchable inventory

With SBOMs stored for each deployed artifact, you can search for the library and version across everything in minutes, including transitive and shaded copies that teams may not know about. Asking teams is slow and incomplete. SAST looks at your code, not bundled libraries.

31. Memory HPA never scales down

A Java service autoscales on average memory utilisation. After a traffic peak it scaled from 3 to 10 replicas, and it stays at 10 all night with almost no traffic. What is the likely reason?

  1. A.The HPA only scales down when CPU also falls under target
  2. B.The JVM keeps heap it grew into, so memory never drops below target
  3. C.Memory metrics are only collected while traffic is high
  4. D.HPA cannot scale down any Deployment with more than 8 replicas
Show answer

Answer: B. The JVM keeps heap it grew into, so memory never drops below target

Many runtimes, the JVM among them, do not give heap back to the OS quickly after a spike, so memory per Pod stays high even when idle. The HPA sees utilisation at target and keeps the replicas. Scale on CPU, request rate or queue length instead, which track load.

32. Google's AROUND operator

What does this Google query aim to find?

"java" AROUND(3) "spring boot" site:linkedin.com/in
  1. A.Profiles that list exactly 3 different Java skills
  2. B.Profiles from the 3 cities nearest to the user
  3. C.Pages where the two terms appear within 3 words
  4. D.Profiles that show 3 or more years of Java work
Show answer

Answer: C. Pages where the two terms appear within 3 words

AROUND(n) is an unofficial Google proximity operator that favours pages where the two terms appear within n words of each other. It helps find skills listed together, though results are not guaranteed, so test it.

Ready to test yourself?

Take a 15-question Java MCQ test with a score at the end, or practise the full Java question bank and earn points on the leaderboard.