Java Developer interview questions
100 real questions with model answers and explanations for Junior candidates.
See a Java Developer resume example →Practice with flashcards
Spaced repetition · Hunter Pass
Questions
The JDK provides development tools, while the JVM executes Java bytecode and the JRE supplies what that execution needs.
- The JDK includes tools such as the javac compiler as well as the runtime components.
- javac compiles Java source files into platform-neutral .class bytecode.
- The JVM loads and executes that bytecode on a specific operating system.
- The JRE traditionally means the JVM plus runtime libraries, although modern Java distributions are usually delivered as JDKs or custom runtime images.
Why interviewers ask this: The interviewer is checking whether you can distinguish the compiler, runtime environment, and virtual machine without treating them as synonyms.
Java is platform-independent because source code is compiled to bytecode that different JVM implementations can execute.
- The compiler targets the JVM instruction set rather than one operating system's machine code.
- Each supported platform has its own JVM that translates or interprets the same bytecode.
- Platform independence still depends on avoiding operating-system-specific APIs and native libraries.
Why interviewers ask this: A strong answer connects portability to bytecode and platform-specific JVM implementations rather than repeating a slogan.
The main method is the conventional entry point the Java launcher calls to start an application.
- Its usual declaration is public static void main(String[] args).
- public lets the launcher access it, and static allows invocation without creating an object.
- String[] args contains command-line arguments, while void means the method returns no value to the caller.
Why interviewers ask this: The interviewer wants to see whether you understand the parts of the entry-point signature rather than only memorizing it.
Declaration introduces a variable and its type, while initialization gives it its first value.
- int count; declares a local variable named count.
- count = 0; assigns a value, and int count = 0; combines declaration with initialization.
- A local variable must be definitely initialized before use, which the compiler verifies.
Why interviewers ask this: This checks basic syntax and awareness of Java's compile-time definite-assignment rule.
Java has eight primitive value types: byte, short, int, long, float, double, char, and boolean.
- byte, short, int, and long represent signed integer values with different ranges.
- float and double represent floating-point values, with double offering greater precision.
- char stores a UTF-16 code unit, while boolean stores true or false.
Why interviewers ask this: The interviewer is evaluating whether your knowledge of Java's type system includes the primitive categories and their purposes.
A primitive variable contains a simple value, while a reference variable identifies an object or can contain null.
- Primitives have fixed language-defined types and do not expose instance methods.
- Objects are created from classes and carry fields and behavior accessed through a reference.
- Assigning a primitive copies its value, while assigning a reference copies the reference to the same object.
Why interviewers ask this: A good answer distinguishes values from references and explains the observable effect of assignment.
Instance and static fields receive default values, but local variables must be initialized explicitly before use.
- Numeric fields default to zero, boolean fields to false, and reference fields to null.
- Array elements also receive the default value of their component type.
- The compiler rejects a path that reads an uninitialized local variable.
Why interviewers ask this: The interviewer is checking an important distinction between object state initialization and local variable rules.
Widening is a primitive conversion Java permits implicitly, while narrowing targets a type that requires an explicit cast.
- Converting int to long is widening and preserves every possible int value.
- Converting long to int is narrowing because an int cannot represent the full long range.
- Narrowing can overflow or lose precision, and even a widening conversion such as int to float can lose numeric precision.
Why interviewers ask this: A strong answer explains both compiler behavior and the risk of data loss.
Autoboxing converts a primitive to its wrapper type automatically, while unboxing extracts the primitive value from a wrapper.
- Assigning an int to an Integer can trigger autoboxing through Integer.valueOf.
- Assigning an Integer to an int can trigger unboxing through intValue.
- Unboxing a null wrapper throws NullPointerException, so wrappers require null awareness.
Why interviewers ask this: The interviewer checks whether you understand the convenience and the null-related risk of wrapper conversions.
For primitives, == compares values, while for object references it tests whether both references point to the same object.
- Two separate objects can contain equal data and still produce false with ==.
- Logical equality between objects is normally checked with equals.
- Comparing a boxed value and a primitive may trigger unboxing, which can hide the difference between identity and value comparison.
Why interviewers ask this: This tests whether you can avoid a common Java bug caused by confusing identity with logical equality.
String is immutable because its character content cannot change after the object is created.
- Operations such as concat, replace, and toUpperCase return a new String rather than modifying the original.
- Immutability makes strings safe to share, cache, and use as map keys when their equality is stable.
- Repeated concatenation in a loop creates many temporary objects, so a mutable builder is usually better there.
Why interviewers ask this: The interviewer is looking for practical consequences of immutability, not just its definition.
The string pool is a JVM-managed store that lets identical interned strings share one object.
- String literals with the same content normally refer to the same pooled instance.
- new String("java") explicitly creates a separate object even if the literal is pooled.
- Pooling saves memory, but string content should still be compared with equals rather than relying on reference identity.
Why interviewers ask this: A strong answer explains pooling while avoiding the mistaken conclusion that == is safe for string comparison.
Use StringBuilder when constructing text through multiple changes within one thread.
- append and related methods modify the same builder instead of creating a new String at every step.
- This reduces temporary allocations in loops or when assembling many fragments.
- Convert the completed value to an immutable String with toString when construction is finished.
Why interviewers ask this: The interviewer checks whether you can connect String immutability to an appropriate construction tool.
A class defines a type's state and behavior, while an object is a runtime instance of that class.
- Fields describe the data each instance can hold.
- Methods describe operations available on instances or on the class itself.
- Multiple objects of one class have the same structure but can hold different field values.
Why interviewers ask this: This foundational question checks whether you distinguish a type definition from the instances created from it.
A constructor initializes a newly created object and has the same name as its class with no return type.
- The new expression allocates an object and invokes a matching constructor.
- Constructors can be overloaded with different parameter lists.
- If a class declares no constructor, the compiler may provide a no-argument default constructor.
Why interviewers ask this: The interviewer is evaluating whether you understand object initialization and the precise rules that distinguish constructors from methods.
this refers to the current object whose instance method or constructor is executing.
- It disambiguates a field from a parameter with the same name, as in this.name = name.
- this(...) calls another constructor in the same class and must be the constructor's first statement.
- It cannot be used in a static context because no current instance exists there.
Why interviewers ask this: A strong answer covers current-instance access, constructor delegation, and the static-context limitation.
A static member belongs to the class rather than to any one instance.
- All instances observe the same static field, so it is suitable for shared class-level state or constants.
- A static method can be called through the class name without constructing an object.
- Static code cannot directly access instance fields or methods because it has no this reference.
Why interviewers ask this: The interviewer checks whether you understand ownership and access rules for class-level members.
final prevents reassignment, overriding, or inheritance depending on where it is applied.
- A final variable can be assigned once, but a final object reference does not make the referenced object immutable.
- A final method cannot be overridden by a subclass.
- A final class cannot be extended, which can preserve its behavior and invariants.
Why interviewers ask this: A good answer distinguishes the three uses of final and avoids equating a final reference with an immutable object.
Encapsulation keeps an object's internal state behind a controlled public interface.
- Fields are commonly private so callers cannot freely put the object into an invalid state.
- Methods can validate changes and preserve class invariants.
- Callers depend on stable behavior rather than the current storage details, making internals easier to change.
Why interviewers ask this: The interviewer wants to hear how access control protects invariants, not merely that getters and setters exist.
Inheritance lets a subclass reuse and specialize accessible behavior from one superclass.
- A class declares the relationship with extends and inherits eligible fields and methods.
- Constructors are not inherited, and a subclass constructor invokes a superclass constructor directly or implicitly.
- Every class except Object has one direct superclass because Java does not support multiple class inheritance.
Why interviewers ask this: A strong answer includes Java's single-inheritance rule and the special treatment of constructors.
Locked questions
- 21
What is the difference between method overloading and method overriding?
oopmethods - 22
What is runtime polymorphism in Java?
oop - 23
What is an abstract class?
oop - 24
What is a Java interface?
typesinterfaces - 25
When would you choose an interface over an abstract class?
typesoopinterfaces - 26
How do Java's public, protected, package-private, and private access levels differ?
basics - 27
What are packages and import declarations used for in Java?
basics - 28
Why is composition often preferred over inheritance?
oopownership - 29
What is the significance of the Object class in Java?
- 30
What contract must equals and hashCode follow?
equals-hashcode - 31
Why would you override toString in a Java class?
methods - 32
Which guarantees does the List interface provide?
typesinterfaces - 33
How do ArrayList and LinkedList differ?
collections - 34
How does a Set differ from other collection types?
collections - 35
How does HashSet decide whether an element is a duplicate?
collections - 36
How does Map represent key-value associations?
- 37
How does HashMap work at a high level?
collections - 38
How do arrays differ from ArrayList in Java?
collections - 39
What are the common ways to iterate over a Java collection?
iterationcollections - 40
What problem do generics solve in Java?
generics - 41
Why is List<Integer> not a subtype of List<Number>?
- 42
What are raw types and why should modern Java code avoid them?
generics - 43
What is the difference between checked and unchecked exceptions?
error-handlingexceptions - 44
How do try, catch, and finally work together?
modifiersexceptions - 45
What is the difference between throw and throws in Java?
- 46
When should you create a custom exception?
error-handlingexceptions - 47
What does try-with-resources do?
exceptions - 48
What are the stack and heap used for in a running Java program?
memorydata-structures - 49
What does garbage collection do in the JVM?
gcjvmcollections - 50
Is Java pass-by-value or pass-by-reference?
- 51
How would you implement a method that normalizes a username before saving it?
normalization - 52
Write the logic for summing only positive integers in a list while handling a null list safely.
fundamentals - 53
How would you remove duplicate email addresses while preserving their original order?
- 54
How would you count word frequencies in a sentence using Java collections?
collections - 55
How would you group a list of orders by customer ID?
- 56
How would you sort employees by salary descending and then by name ascending?
- 57
How would you merge two inventory maps by adding quantities for matching product IDs?
- 58
How would you remove expired sessions from a mutable list without causing ConcurrentModificationException?
sessionsconcurrency - 59
How would you implement a FIFO queue of background jobs with standard Java collections?
data-structurescollectionsjobs - 60
How would you find the intersection of two lists without returning duplicate values?
- 61
How would you return the top three most frequent error codes from a list?
- 62
A user lookup in a map sometimes causes an NPE. How would you debug and fix it?
- 63
How would you diagnose a ClassCastException when reading values from a legacy Map?
- 64
Why can adding an element to List.of fail at runtime, and how would you fix the code?
- 65
A HashMap lookup fails for a key object that appears equal. What would you inspect?
collections - 66
How would you implement age validation with a custom exception?
error-handlingexceptionsvalidation - 67
How would you read a text file and guarantee that it is closed if parsing fails?
- 68
How would you parse a list of numeric strings when invalid entries should be reported but valid entries retained?
strings - 69
Where would you catch an exception thrown by a repository method?
error-handlingexceptions - 70
How would you preserve useful debugging information when converting one exception into another?
error-handlingexceptions - 71
How would you ensure a temporary status flag is reset even when an operation throws?
- 72
How would you implement a thread-safe request counter in Java?
concurrency - 73
How would you run ten independent tasks using a fixed number of worker threads?
concurrency - 74
A worker thread is interrupted while waiting. How should its code respond?
concurrency - 75
How would you share a queue safely between a producer thread and a consumer thread?
concurrencydata-structures - 76
Two threads update a shared ArrayList and results are missing. How would you fix it?
concurrencycollections - 77
How would you avoid a simple deadlock when two methods need the same two locks?
lockingconcurrency - 78
How would you make a configuration object safe to share between threads?
concurrencyconfig - 79
How would you find the cause of an IndexOutOfBoundsException in a loop?
indexes - 80
A stream pipeline throws an NPE in map(String::length). How would you repair it?
ci-cdstrings - 81
How would you implement a palindrome check that ignores case and non-letter characters?
- 82
How would you reverse the order of words in a sentence without reversing the letters?
- 83
How would you find the second-largest distinct integer in an array?
distinct - 84
How would you detect whether an array contains any duplicate value?
- 85
How would you implement binary search on a sorted int array?
algorithms - 86
How would you check whether two strings are anagrams?
strings - 87
How would you validate that brackets in a string are balanced?
validationstrings - 88
How would you calculate the nth Fibonacci number without recursion?
recursion - 89
An array contains numbers from 1 to n with one number missing. How would you find it?
- 90
How would you rotate a list to the right by k positions?
- 91
How would you merge two sorted int arrays into one sorted array?
- 92
How would you find the first non-repeating character in a string?
strings - 93
How would you remove duplicates from a sorted array in place?
- 94
How would you find a pair of numbers whose sum equals a target?
equals-hashcode - 95
How would you calculate totals per category from a list of transactions?
transactions - 96
How would you implement a method that retries a flaky operation at most three times?
flaky - 97
How would you safely convert an Object value to an integer when input may be an Integer or a numeric String?
strings - 98
How would you update a shared cache of user sessions from multiple threads?
concurrencycachingsessions - 99
How would you debug a method that returns the right values but in an unpredictable order?
- 100
How would you implement a small service method that loads an order, verifies ownership, and marks it cancelled?
ownership