Skip to content

Java Developer Interview Questions & Answers

40 questions for Java Developer interviews — 26 easy, 12 medium, 2 hard.

About the Java Developer role

A Java developer builds and maintains server side applications using core Java, OOP and common libraries. Freshers in this role write features, fix bugs, write unit tests and work with SQL databases under senior guidance. It is the most common entry role at IT services companies and global capability centres, and it builds the base for backend, full stack and architect careers.

Core Java OOP Collections SQL Git
Solved for this roleStart 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 autoboxing and what pitfall can it cause?

Save to ▾
Show answer
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.
02

What is the difference between method overloading and method overriding?

Save to ▾
Show answer
Overloading means several methods in the same class share a name but differ in parameter list; it is resolved at compile time. Overriding means a subclass provides its own version of a parent method with the same signature; it is resolved at runtime through dynamic dispatch. Return type alone cannot overload a method, while overriding allows a covariant return type.
03

Write a Java method to check whether a string is a palindrome, ignoring case and non-letters.

Save to ▾
Show answer
Use two pointers from both ends. public static boolean isPalindrome(String s) { int i = 0, j = s.length() - 1; while (i < j) { char a = s.charAt(i), b = s.charAt(j); if (!Character.isLetterOrDigit(a)) { i++; continue; } if (!Character.isLetterOrDigit(b)) { j--; continue; } if (Character.toLowerCase(a) != Character.toLowerCase(b)) return false; i++; j--; } return true; } Time O(n), space O(1).
04

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

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

What is the difference between JDK, JRE and JVM?

Save to ▾
Show answer
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.
07

Objects used as HashMap keys cannot be found after insertion. What could be wrong?

Save to ▾
Show answer
Most likely the class overrides equals() but not hashCode(), or neither, so equal keys land in different buckets. Another cause is a mutable key: a field used in hashCode() was changed after insertion, so the lookup goes to a different bucket. The fix is to implement both methods on the same fields and use immutable keys such as String, records or final classes.
08

What is the difference between start() and run()?

Save to ▾
Show answer
start() asks the JVM to create a new thread and then calls run() on that new thread, so the code executes concurrently. Calling run() directly is just a normal method call on the current thread, so no new thread is created. Calling start() twice on the same Thread throws IllegalThreadStateException.
09

Write a Java solution for the Two Sum problem using a HashMap.

Save to ▾
Show answer
Store each number's index and look up its complement. public int[] twoSum(int[] nums, int target) { Map<Integer, Integer> seen = new HashMap<>(); for (int i = 0; i < nums.length; i++) { Integer j = seen.get(target - nums[i]); if (j != null) return new int[]{j, i}; seen.put(nums[i], i); } return new int[0]; } One pass, O(n) time and O(n) space.
10

What is constructor chaining?

Save to ▾
Show answer
Constructor chaining is calling one constructor from another. this(...) calls another constructor in the same class and super(...) calls a parent class constructor; either must be the first statement. If you write neither, the compiler inserts super() automatically. Chaining avoids duplicate initialisation code, for example a no-arg constructor calling this("default", 0).
11

Find the first non-repeating character in a string.

Save to ▾
Show answer
Count in one pass, then scan again in order. public static char firstUnique(String s) { int[] cnt = new int[128]; for (char c : s.toCharArray()) cnt[c]++; for (char c : s.toCharArray()) { if (cnt[c] == 1) return c; } return '_'; } Two passes, O(n) time and O(1) extra space for ASCII input.
12

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

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

Why are String objects immutable in Java?

Save to ▾
Show answer
Strings are immutable so they can be safely shared from the string pool, used as HashMap keys with a cached hash code, passed between threads without locking and trusted in security checks such as file paths and class names. Any change, like concat or replace, creates a new String. For heavy modification use StringBuilder, which changes its internal buffer in place.
15

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

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

What is the String constant pool?

Save to ▾
Show answer
The string pool is a special area in the heap where string literals are stored once and reused. String a = "hi" and String b = "hi" point to the same object. new String("hi") creates a separate heap object, and intern() returns the pooled copy. Pooling saves memory because many strings in apps repeat, such as status codes and keys.
17

What are fail-fast and fail-safe iterators?

Save to ▾
Show answer
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.
18

Remove duplicates from a list while keeping the original order.

Save to ▾
Show answer
A LinkedHashSet keeps first-seen order. List<String> unique = new ArrayList<>(new LinkedHashSet<>(names)); // or with streams List<String> unique2 = names.stream() .distinct() .toList(); Both rely on equals() and hashCode(), and both run in O(n) on average.
19

Why did you choose Java for your career?

Save to ▾
Show answer
Situation: in college I tried several languages for projects. Task: I wanted one that leads to stable, well paid work. Action: I found Java powers banking, ecommerce and enterprise backends, has strong tooling and a huge job market, so I built two Spring Boot projects and practised DSA in Java. Result: I am confident in the language and keen to keep learning modern features like records and virtual threads.
20

Count the frequency of each character in a string using Java.

Save to ▾
Show answer
A map with merge() is simple; streams also work. Map<Character, Integer> freq = new LinkedHashMap<>(); for (char c : s.toCharArray()) { freq.merge(c, 1, Integer::sum); } // Streams version Map<Character, Long> f = s.chars() .mapToObj(c -> (char) c) .collect(Collectors.groupingBy(c -> c, LinkedHashMap::new, Collectors.counting())); LinkedHashMap keeps first-seen order.
21

What is the difference between final, finally and finalize?

Save to ▾
Show answer
final is a keyword: a final variable cannot be reassigned, a final method cannot be overridden and a final class cannot be extended. finally is a block that runs after try-catch whether or not an exception occurs, used for cleanup. finalize() was a method called before garbage collection; it is deprecated for removal and should be replaced with try-with-resources or Cleaner.
22

You need to remove items from an ArrayList while looping over it. How do you do it safely?

Save to ▾
Show answer
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.
23

What are the four pillars of OOP? Explain with Java examples.

Save to ▾
Show answer
Encapsulation hides data behind methods, for example private fields with getters and setters in a BankAccount class. Abstraction exposes only what is needed through abstract classes or interfaces, like a Payment interface. Inheritance lets a class reuse another, such as SavingsAccount extends Account. Polymorphism lets one reference behave differently, like a Payment variable calling pay() on a UpiPayment or CardPayment.
24

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

What are text blocks in Java?

Save to ▾
Show answer
Text blocks, final in Java 15, are multi-line string literals written between triple double quotes. They keep line breaks, remove common leading indentation and need far fewer escape characters, which makes embedded JSON, SQL and HTML readable. Methods like formatted() can insert values. They are still normal String objects in the pool.
26

An application gets StackOverflowError in a recursive method. What do you do?

Save to ▾
Show answer
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.
27

What is try-with-resources?

Save to ▾
Show answer
Try-with-resources, from Java 7, automatically closes any object that implements AutoCloseable when the try block ends, even if an exception is thrown. Resources close in reverse order of opening. If both the body and close() throw, the close exception is added as a suppressed exception. It replaces long finally blocks for files, JDBC connections and streams.
28

What is the difference between == and equals() in Java?

Save to ▾
Show answer
== compares primitive values, or for objects it checks whether two references point to the same object in memory. equals() checks logical equality and can be overridden, as String, Integer and most value classes do. For example, new String("a") == new String("a") is false, but equals() returns true. Always use equals() to compare object content.
29

How do you make a class immutable in Java?

Save to ▾
Show answer
Declare the class final, make all fields private and final, set them only in the constructor, and provide no setters. For mutable fields like a List or Date, make defensive copies in the constructor and in getters, or use List.copyOf. Immutable objects are thread safe and make good map keys. Java records give a concise way to create shallowly immutable data classes.
30

Why does Java not support multiple inheritance of classes?

Save to ▾
Show answer
Multiple inheritance of classes creates the diamond problem: if two parents have the same method with different code, the child cannot know which one to use, and state duplication becomes messy. Java avoids this by allowing one superclass but many interfaces. If two interfaces provide the same default method, the class must override it and can call a specific one with InterfaceName.super.method().
31

Why is Java called platform independent?

Save to ▾
Show answer
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.
32

What is CompletableFuture and how is it better than Future?

Save to ▾
Show answer
Future only lets you block with get() to obtain a result. CompletableFuture supports non-blocking composition: thenApply to transform, thenCompose to chain async calls, thenCombine or allOf to join several, and exceptionally or handle for errors. It runs on the common ForkJoinPool by default, but pass your own executor for blocking I/O to avoid starving the pool.
33

Sort a list of employees by department, then by salary descending.

Save to ▾
Show answer
Chain comparators. employees.sort( Comparator.comparing(Employee::department) .thenComparing(Employee::salary, Comparator.reverseOrder())); // Streams version returning a new list List<Employee> sorted = employees.stream() .sorted(Comparator.comparing(Employee::department) .thenComparing(Employee::salary, Comparator.reverseOrder())) .toList(); List.sort is stable, so equal keys keep their order.
34

Write a Java program to check whether a number is prime.

Save to ▾
Show answer
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.
35

What is the difference between Comparable and Comparator?

Save to ▾
Show answer
Comparable defines a class's natural ordering through compareTo() inside the class, such as String sorted alphabetically. Comparator is a separate object with compare(), so you can define many orderings without changing the class. Java 8 made Comparator easy: Comparator.comparing(Employee::getSalary).reversed().thenComparing(Employee::getName). TreeMap and sort methods accept either.
36

What is the difference between a static and an instance variable?

Save to ▾
Show answer
A static variable belongs to the class, so there is only one copy shared by all objects, and it is created when the class is loaded. An instance variable belongs to each object and gets a separate copy per instance. A counter of created objects should be static, while a customer's name should be an instance field.
37

How do you handle disagreement with a reviewer about your code?

Save to ▾
Show answer
Situation: a senior reviewer asked me to replace my checked exceptions with unchecked ones. Task: decide the right approach without conflict. Action: I asked for the reasons, read our codebase conventions and wrote a small comparison, then agreed because unchecked exceptions fit our global handler. Result: the change merged the same day and I learned to check team conventions before designing error handling.
38

A team member compares two Integer values with == and the check fails only for large numbers. Explain.

Save to ▾
Show answer
Integer.valueOf caches objects for values from -128 to 127, so autoboxed small numbers share the same object and == returns true. Larger values create new Integer objects, so == compares two different references and returns false. The fix is to use equals() or compare unboxed int values. Static analysis tools like SonarQube flag this pattern.
39

Explain the main memory areas of the JVM.

Save to ▾
Show answer
The heap stores all objects and is shared by threads; it is managed by the garbage collector. Each thread has its own stack holding frames with local variables and partial results. Metaspace (native memory since Java 8) stores class metadata. There are also the program counter register and native method stacks. StackOverflowError comes from the stack and OutOfMemoryError usually from heap or metaspace.
40

What is the difference between throw and throws?

Save to ▾
Show answer
throw is a statement used inside a method to actually raise an exception object, for example throw new IllegalStateException("closed"). throws is used in a method signature to declare which checked exceptions the method may pass to its caller, for example void read() throws IOException. A method can declare many exceptions with throws but throws one object at a time.

Frequently asked questions

What does a Java Developer do?

A Java developer builds and maintains server side applications using core Java, OOP and common libraries. Freshers in this role write features, fix bugs, write unit tests and work with SQL databases under senior guidance. It is the most common entry role at IT services companies and global capability centres, and it builds the base for backend, full stack and architect careers.

Which skills are tested in a Java Developer interview?

Expect questions on Core Java, OOP, Collections, SQL, Git. Most rounds also ask you to explain a project and solve one practical problem live.

How do I prepare for a Java Developer interview?

Revise Java Basics and JVM, OOP in Java, Collections Framework, Strings and Exception Handling first using the topic sheets, practise the questions on this page aloud, then do one full mock interview to practise timing.