Quick answer: These 72 Java interview questions and answers cover what is asked most in Java developer, software engineer and campus placement interviews: Java basics, OOP, strings, exception handling, the collections framework, multithreading, Java 8 features, JVM memory management and common coding questions. Key answers include short code examples.
Read each answer, then close the page and explain it aloud in two or three sentences. That is exactly what interviewers check.
Contents
- Java Basics
- Object-Oriented Programming
- Strings
- Exception Handling
- Collections Framework
- Multithreading and Concurrency
- Java 8 and Modern Java
- Memory Management and JVM
- Coding Questions
- How to prepare
- FAQs
1. Java Basics Interview Questions
Q1. What is Java?
Java is a high-level, object-oriented, class-based programming language. Its main idea is 'write once, run anywhere': code is compiled to bytecode that runs on any device with a Java Virtual Machine. It is used for Android apps, enterprise back ends, banking systems and big-data tools.
Q2. What are the main features of Java?
Java is platform independent, object-oriented, strongly typed, secure (no direct pointers, bytecode verification), robust (automatic garbage collection and exception handling), multithreaded, and has a very large standard library.
Q3. What is the difference between JDK, JRE and JVM?
The JVM runs Java bytecode. The JRE is the JVM plus the core libraries needed to run programs. The JDK is the JRE plus development tools such as the compiler (javac) and debugger. Developers install the JDK.
Q4. Why is Java platform independent?
The javac compiler turns source code into bytecode (.class files), not machine code. Each operating system has its own JVM that translates the same bytecode into native instructions, so one compiled program runs on Windows, Linux or macOS.
Q5. What is the JIT compiler?
The Just-In-Time compiler inside the JVM converts frequently executed bytecode into native machine code while the program runs. This makes Java much faster than pure interpretation.
Q6. Explain public static void main(String[] args).
public lets the JVM call the method from outside the class; static lets it run without creating an object; void means it returns nothing; main is the name the JVM looks for; and String[] args holds command-line arguments.
public class Hello {
public static void main(String[] args) {
System.out.println("Hello, Java");
}
}Q7. What are the primitive data types in Java?
Java has eight primitives: byte, short, int, long (whole numbers), float, double (decimals), char (a single Unicode character) and boolean. Everything else, including String and arrays, is a reference type.
Q8. What are wrapper classes and autoboxing?
Wrapper classes (Integer, Double, Character, Boolean and so on) wrap primitives as objects so they can be used in collections. Autoboxing converts a primitive to its wrapper automatically, and unboxing does the reverse.
List<Integer> nums = new ArrayList<>();
nums.add(5); // autoboxing int -> Integer
int x = nums.get(0); // unboxing Integer -> intQ9. Is Java pass-by-value or pass-by-reference?
Java is always pass-by-value. For objects, the value passed is a copy of the reference, so a method can change the object's fields but cannot make the caller's variable point to a different object.
Q10. What is the difference between == and equals()?
== compares primitive values, or for objects checks whether two references point to the same object. equals() compares the content of objects when the class overrides it, as String does.
2. Object-Oriented Programming Interview Questions
Q11. What are the four pillars of OOP?
Encapsulation (hiding data behind methods), inheritance (reusing a parent class), polymorphism (one interface, many forms) and abstraction (showing only essential features through abstract classes and interfaces).
Q12. What is a class and what is an object?
A class is a blueprint that defines fields and methods. An object is an instance of a class created with new, with its own copy of the fields. For example, Car is a class and myCar = new Car() is an object.
Q13. What is a constructor?
A constructor is a special method with the same name as the class and no return type. It runs when an object is created and initialises its fields. If you write none, Java provides a default no-argument constructor.
Q14. What is constructor overloading and constructor chaining?
Overloading means having several constructors with different parameter lists. Chaining means one constructor calls another in the same class with this(…) or the parent constructor with super(…), which must be the first statement.
Q15. What is encapsulation?
Encapsulation keeps fields private and exposes them through public getter and setter methods, so the class controls how its data is read and changed.
public class Account {
private double balance;
public double getBalance() { return balance; }
public void deposit(double amt) {
if (amt > 0) balance += amt;
}
}Q16. What is inheritance? Which types does Java support?
Inheritance lets a class reuse the fields and methods of another using extends. Java supports single, multilevel and hierarchical inheritance with classes. Multiple inheritance of classes is not allowed, but a class can implement many interfaces.
Q17. Why does Java not support multiple inheritance with classes?
To avoid the diamond problem: if two parent classes had the same method, the compiler could not decide which one to inherit. Interfaces solve this, and with default methods Java forces the class to override any conflicting method.
Q18. What is polymorphism?
Polymorphism lets the same method call behave differently. Compile-time polymorphism is method overloading. Runtime polymorphism is method overriding, where a parent reference calls the child's version of a method.
Q19. What is the difference between method overloading and overriding?
Overloading: same method name, different parameters, in the same class, resolved at compile time. Overriding: same name and parameters in a subclass, replacing the parent's behaviour, resolved at runtime.
class Shape { double area() { return 0; } }
class Circle extends Shape {
double r = 2;
@Override
double area() { return Math.PI * r * r; }
}
Shape s = new Circle();
System.out.println(s.area()); // Circle's version runsQ20. What is abstraction?
Abstraction hides implementation details and shows only what an object does. In Java it is achieved with abstract classes and interfaces.
Q21. What is the difference between an abstract class and an interface?
An abstract class can have constructors, instance fields and both abstract and concrete methods, and a class can extend only one. An interface defines a contract; its fields are public static final, it can have default and static methods (Java 8+), and a class can implement many.
Q22. What are the uses of the this and super keywords?
this refers to the current object, for example to separate a field from a parameter with the same name, or to call another constructor. super refers to the parent class, to call its constructor or an overridden method.
Q23. What does the final keyword do?
A final variable cannot be reassigned, a final method cannot be overridden, and a final class cannot be extended (String is final).
Q24. What does the static keyword mean?
A static field or method belongs to the class, not to any object, so it is shared by all instances and can be used without creating an object. Static blocks run once when the class is loaded.
Q25. What are access modifiers in Java?
private: only inside the class. Default (no modifier): inside the same package. protected: same package plus subclasses. public: everywhere.
3. Strings Interview Questions
Q26. Why is String immutable in Java?
Once created, a String cannot change. This makes strings safe to share between threads, allows the string pool to reuse them, keeps hash codes stable for HashMap keys, and protects values such as file paths and URLs.
Q27. What is the String pool?
The String pool is a special memory area in the heap that stores string literals. When two literals have the same text, they share one object, which saves memory. new String("hi") always creates a new object outside the pool.
Q28. What is the difference between String, StringBuilder and StringBuffer?
String is immutable. StringBuilder is mutable and fast but not thread-safe. StringBuffer is mutable and thread-safe because its methods are synchronised, so it is slower. Use StringBuilder for building strings in loops.
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 3; i++) sb.append(i);
System.out.println(sb); // 012Q29. How do you reverse a string in Java?
The simplest way is StringBuilder.reverse(). In interviews you may also be asked to do it with a loop.
String s = "java";
String rev = new StringBuilder(s).reverse().toString();
// manual
String r = "";
for (int i = s.length() - 1; i >= 0; i--) r += s.charAt(i);4. Exception Handling Interview Questions
Q30. What is an exception?
An exception is an event that disrupts the normal flow of a program, such as dividing by zero or opening a missing file. Java represents it as an object, and you handle it with try, catch and finally.
Q31. What is the difference between checked and unchecked exceptions?
Checked exceptions (such as IOException and SQLException) are checked at compile time, so you must catch them or declare them with throws. Unchecked exceptions (subclasses of RuntimeException, such as NullPointerException) are not checked by the compiler.
Q32. What is the difference between an Error and an Exception?
Errors, such as OutOfMemoryError and StackOverflowError, are serious problems in the JVM that programs usually should not catch. Exceptions are conditions the program can reasonably handle.
Q33. What is the difference between throw and throws?
throw is used inside a method to actually throw an exception object. throws is used in the method signature to declare which checked exceptions the method may pass to its caller.
Q34. Does the finally block always run?
finally runs whether or not an exception occurs, even after a return in try. It does not run if the JVM exits with System.exit() or crashes. It is used to close resources.
Q35. What is try-with-resources?
Introduced in Java 7, it automatically closes resources that implement AutoCloseable, such as files and database connections, at the end of the try block.
try (BufferedReader br = new BufferedReader(new FileReader("a.txt"))) {
System.out.println(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}Q36. How do you create a custom exception?
Extend Exception for a checked exception or RuntimeException for an unchecked one, and pass a message to the parent constructor.
class InsufficientBalanceException extends Exception {
InsufficientBalanceException(String msg) { super(msg); }
}5. Collections Framework Interview Questions
Q37. What is the Java Collections Framework?
It is a set of interfaces (List, Set, Queue, Map) and classes (ArrayList, LinkedList, HashSet, TreeSet, HashMap, TreeMap, PriorityQueue and more) for storing and processing groups of objects, with ready algorithms for sorting and searching.
Q38. What is the difference between ArrayList and LinkedList?
ArrayList uses a dynamic array, so get(index) is O(1) but inserting or removing in the middle is O(n). LinkedList uses a doubly linked list, so adding or removing at the ends is O(1) but access by index is O(n). ArrayList is the usual choice.
Q39. What is the difference between List, Set and Map?
A List is ordered and allows duplicates. A Set stores unique elements. A Map stores key-value pairs with unique keys. Map does not extend the Collection interface.
Q40. How does HashMap work internally?
HashMap stores entries in an array of buckets. The key's hashCode() picks the bucket, and equals() finds the right key inside it. Collisions are stored in a linked list, which becomes a balanced tree when a bucket grows beyond 8 entries (Java 8+). When it is 75% full, it doubles its size and rehashes.
Q41. Why must you override hashCode() when you override equals()?
Hash-based collections first use hashCode() to find a bucket, then equals() to compare. If two equal objects have different hash codes, HashMap and HashSet will treat them as different keys and duplicates will appear.
Q42. What is the difference between HashMap, LinkedHashMap and TreeMap?
HashMap has no guaranteed order and O(1) average operations. LinkedHashMap keeps insertion order. TreeMap keeps keys sorted and has O(log n) operations.
Q43. What is the difference between HashMap and Hashtable?
HashMap is not synchronised, allows one null key and many null values, and is faster. Hashtable is synchronised and allows no nulls. For thread-safe maps, use ConcurrentHashMap instead of Hashtable.
Q44. What is the difference between HashSet and TreeSet?
HashSet stores unique elements in no particular order with O(1) average operations. TreeSet keeps elements sorted, with O(log n) operations.
Q45. What is the difference between Comparable and Comparator?
Comparable defines a class's natural order through compareTo() inside the class. Comparator defines a separate ordering through compare(), so you can sort the same objects in different ways.
List<Student> list = ...;
list.sort(Comparator.comparing(Student::getMarks).reversed());Q46. What is the difference between fail-fast and fail-safe iterators?
Fail-fast iterators, used by ArrayList and HashMap, throw ConcurrentModificationException if the collection is modified during iteration. Fail-safe iterators, used by concurrent collections such as CopyOnWriteArrayList, work on a copy or snapshot and do not throw.
6. Multithreading and Concurrency Interview Questions
Q47. What is a thread?
A thread is the smallest unit of execution inside a process. Several threads in one program share memory and can run tasks in parallel, such as downloading a file while keeping the screen responsive.
Q48. How do you create a thread in Java?
Extend Thread and override run(), or implement Runnable and pass it to a Thread. Implementing Runnable (or using an ExecutorService) is preferred because the class can still extend another class.
Runnable task = () -> System.out.println("Running in " + Thread.currentThread().getName());
Thread t = new Thread(task);
t.start();Q49. What is the difference between start() and run()?
start() creates a new thread and then calls run() inside it. Calling run() directly just runs the method in the current thread, like a normal method call.
Q50. What are the states of a thread?
NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING and TERMINATED.
Q51. What is synchronization?
Synchronization lets only one thread at a time run a block or method that uses a shared object's lock. It prevents race conditions, where two threads update shared data at the same time and corrupt it.
Q52. What is the volatile keyword?
volatile makes every read and write of a variable go directly to main memory, so all threads see its latest value. It guarantees visibility but not atomicity, so count++ on a volatile variable is still unsafe.
Q53. What is a deadlock and how can you avoid it?
A deadlock happens when two threads each hold a lock the other needs and wait forever. Avoid it by always acquiring locks in the same order, using timeouts with tryLock, and keeping locked sections small.
Q54. What is the difference between wait() and sleep()?
wait() belongs to Object, must be called inside synchronized code, and releases the lock until notify() is called. sleep() belongs to Thread, pauses for a set time and does not release any lock.
Q55. What is an ExecutorService?
ExecutorService manages a pool of reusable threads, so you submit tasks instead of creating threads yourself. It improves performance and control.
ExecutorService pool = Executors.newFixedThreadPool(4);
Future<Integer> f = pool.submit(() -> 2 + 3);
System.out.println(f.get());
pool.shutdown();7. Java 8 and Modern Java Interview Questions
Q56. What are the main features of Java 8?
Lambda expressions, functional interfaces, the Stream API, default and static methods in interfaces, Optional, method references and the new java.time date and time API.
Q57. What is a lambda expression?
A lambda is a short anonymous function written as (parameters) -> expression. It implements a functional interface and makes code shorter, especially with collections and streams.
List<String> names = List.of("Ravi", "Anu", "Kiran");
names.forEach(n -> System.out.println(n));Q58. What is a functional interface?
A functional interface has exactly one abstract method, so it can be implemented with a lambda. Examples are Runnable, Comparator, Predicate, Function, Consumer and Supplier. The @FunctionalInterface annotation makes the compiler check it.
Q59. What is the Stream API?
Streams process collections in a declarative pipeline of operations such as filter, map, sorted and collect. Intermediate operations are lazy and run only when a terminal operation is called.
List<Integer> evensSquared = nums.stream()
.filter(n -> n % 2 == 0)
.map(n -> n * n)
.collect(Collectors.toList());Q60. What is the difference between map() and flatMap()?
map() transforms each element into exactly one new element. flatMap() transforms each element into a stream and flattens all those streams into one, for example turning a list of lists into a single list.
Q61. What is Optional?
Optional is a container that may or may not hold a value. It makes 'no result' explicit and helps avoid NullPointerException, through methods such as orElse, ifPresent and map.
Q62. What are records in Java?
Records (Java 16+) are compact classes for immutable data. Declaring record Point(int x, int y) automatically generates the constructor, getters, equals(), hashCode() and toString().
8. Memory Management and JVM Interview Questions
Q63. What is the difference between stack and heap memory?
Each thread has its own stack, which stores method calls and local primitive variables and references; it is freed automatically when the method returns. The heap is shared by all threads and stores objects, which the garbage collector cleans up.
Q64. What is garbage collection?
Garbage collection automatically frees heap memory used by objects that are no longer reachable from any live reference. The JVM uses generations: most objects die young in the young generation, and long-lived objects move to the old generation.
Q65. Can a memory leak happen in Java?
Yes. If objects remain referenced but are never used again, for example in a static list or cache that keeps growing, the garbage collector cannot free them and memory runs out.
Q66. What is a ClassLoader?
A ClassLoader loads .class files into the JVM when they are first needed. The bootstrap loader loads core Java classes, the platform loader loads extension modules, and the application loader loads your own classes.
Q67. What is serialization?
Serialization converts an object into a byte stream so it can be saved to a file or sent over a network, and deserialization rebuilds it. A class must implement Serializable, and fields marked transient are skipped.
9. Coding Questions Interview Questions
Q68. How do you check whether a number is prime in Java?
Check divisibility only up to the square root of the number.
static boolean isPrime(int n) {
if (n < 2) return false;
for (int i = 2; (long) i * i <= n; i++)
if (n % i == 0) return false;
return true;
}Q69. How do you check whether a string is a palindrome?
Compare characters from both ends moving inwards.
static boolean isPalindrome(String s) {
int i = 0, j = s.length() - 1;
while (i < j)
if (s.charAt(i++) != s.charAt(j--)) return false;
return true;
}Q70. How do you count the frequency of each character in a string?
Use a HashMap and merge counts.
Map<Character, Integer> freq = new HashMap<>();
for (char c : "banana".toCharArray())
freq.merge(c, 1, Integer::sum);
System.out.println(freq); // {a=3, b=1, n=2}Q71. How do you find the second largest number in an array?
Track the largest and second largest in one pass.
int first = Integer.MIN_VALUE, second = Integer.MIN_VALUE;
for (int x : arr) {
if (x > first) { second = first; first = x; }
else if (x > second && x != first) second = x;
}Q72. How do you swap two numbers without a third variable?
Use addition and subtraction (watch for overflow with very large values).
a = a + b;
b = a - b;
a = a - b;How to Prepare for a Java Interview
- Master OOP first: be ready to explain all four pillars with your own small examples.
- Know collections deeply: HashMap internals, ArrayList versus LinkedList and equals/hashCode are asked almost everywhere.
- Write code on paper: practise string, array and number programs without an IDE.
- Learn Java 8: lambdas, streams and Optional are expected even for freshers.
- Build one project: a library, banking or inventory system you can explain end to end.
Next steps: strengthen problem solving with DSA interview questions, test yourself with the DSA MCQs, and pick a project from our final year projects for computer science.
More interview preparation: see all interview questions, including Python, SQL, SQL query, Java, JavaScript, React, C++, .NET, Spring Boot, Node.js, DSA, OOPs, DBMS, operating system, networking, machine learning, data science, AI, Excel, Power BI, DevOps, manual testing, Selenium, cyber security and HR.
Frequently Asked Questions
Which Java topics are most asked in fresher interviews?
OOP concepts, the difference between abstract class and interface, String immutability, exception handling, HashMap internals, ArrayList versus LinkedList, and Java 8 streams and lambdas come up in almost every interview.
Is Java still worth learning?
Yes. Java powers a large share of enterprise back ends, banking systems and Android apps, and service companies hire Java developers in large numbers every year.
Which Java version should I learn?
Learn a current long-term-support version such as Java 17 or 21. The core concepts are the same, and you also get modern features such as records and improved switch expressions.
How should I prepare for a Java interview?
Revise the questions on this page, write small programs every day, practise collections and string problems, and build one project, such as a library or banking system, that you can explain end to end.