Java interview questions for freshers (with answers)
18 min readUpdated
These are the Java questions that come up again and again in fresher and campus interviews. Each answer is short enough to say out loud in an interview, and the tricky ones come with a small program you can run to see it for yourself.
How to use this list
- Read the question and answer it out loud before you read the answer.
- For every program, guess the output first, then check it.
- If an answer feels new, open the linked lesson at the end and learn the topic properly. Interviewers ask follow-up questions.
Java basics
1. What is the difference between JDK, JRE and JVM?
The JVM (Java Virtual Machine) runs compiled bytecode. The JRE (Java Runtime Environment) is the JVM plus the standard libraries a program needs to run. The JDK (Java Development Kit) is the JRE plus developer tools such as the compiler javac. You write code with the JDK; users only need a runtime to run it.
2. Why is Java called platform independent?
javac compiles your code into bytecode (.class files), not into machine code for one operating system. Any machine with a JVM can run that bytecode, so the same .class file runs on Windows, Linux and macOS. The JVM itself is platform specific; your program is not.
3. Why is main declared public static void?
public so the JVM can call it from outside the class, static so it can be called without creating an object first, and void because it returns nothing to the JVM. String[] args holds the command-line arguments.
4. What are the eight primitive types in Java?
byte, short, int, long (whole numbers), float, double (decimals), char (one character) and boolean (true/false). Everything else, including String and arrays, is a reference type.
5. Is Java pass by value or pass by reference?
Always pass by value. For a primitive, the value is copied. For an object, the reference is copied, so the method can change the object's fields, but reassigning the parameter does not change the caller's variable.
public class PassByValue {
static void change(int n, StringBuilder sb) {
n = 99; // changes only the copy
sb.append(" world"); // changes the shared object
sb = new StringBuilder("new"); // changes only the copied reference
}
public static void main(String[] args) {
int n = 1;
StringBuilder sb = new StringBuilder("hello");
change(n, sb);
System.out.println(n);
System.out.println(sb);
}
}Output
1 hello world
6. What is the difference between == and equals()?
== compares references for objects (are these the same object?) and values for primitives. equals() compares content, as defined by the class. For strings, always use equals().
public class StringCompare {
public static void main(String[] args) {
String a = "java";
String b = "java";
String c = new String("java");
System.out.println(a == b); // same object from the string pool
System.out.println(a == c); // new String creates a different object
System.out.println(a.equals(c)); // same characters
}
}Output
true false true
7. Why are strings immutable in Java?
Once created, a String cannot change; methods like toUpperCase() return a new string. This makes strings safe to share (the string pool reuses them), safe as HashMap keys (the hash code never changes) and safe across threads.
8. What is the difference between String, StringBuilder and StringBuffer?
String is immutable. StringBuilder is mutable and fast, the right choice for building text in a loop. StringBuffer is also mutable but its methods are synchronized, so it is slower; you rarely need it today.
9. What does the final keyword do?
On a variable, the value cannot be reassigned. On a method, it cannot be overridden. On a class, it cannot be extended (String is a final class). A final reference still lets you change the object it points to.
10. What does static mean?
A static field or method belongs to the class, not to each object. There is one copy shared by all objects, and you can use it without creating an object, for example Math.max(3, 7).
Object-oriented programming
11. What are the four pillars of OOP?
Encapsulation (keep data private and expose methods), inheritance (a class reuses another class with extends), polymorphism (one call behaves differently depending on the actual object) and abstraction (show what an object does, hide how).
12. What is the difference between overloading and overriding?
Overloading is the same method name with different parameters in the same class, chosen at compile time. Overriding is a subclass giving its own version of an inherited method with the same signature, chosen at run time based on the actual object.
public class Shapes {
static class Shape {
String name() { return "shape"; }
}
static class Circle extends Shape {
@Override
String name() { return "circle"; }
}
static int area(int side) { return side * side; }
static int area(int width, int height) { return width * height; }
public static void main(String[] args) {
Shape s = new Circle(); // variable type Shape, object type Circle
System.out.println(s.name()); // overriding: decided at run time
System.out.println(area(4)); // overloading: decided at compile time
System.out.println(area(4, 5));
}
}Output
circle 16 20
13. What is the difference between an abstract class and an interface?
An abstract class can have fields, constructors and both finished and abstract methods; a class can extend only one. An interface describes a capability; since Java 8 it can have default and static methods, but no instance fields, and a class can implement many. Use an abstract class for a shared base with state, an interface for a role many unrelated classes can play.
14. Why does Java not support multiple inheritance of classes?
To avoid the diamond problem: if two parent classes had the same method, the child would not know which one to use. Java allows a class to implement many interfaces instead; if two default methods clash, the class must override the method and choose.
15. What is a constructor? Can it be private?
A constructor sets up a new object; it has the class name and no return type. Yes, it can be private, which stops other classes from calling new. This is used in singletons and in utility classes with only static methods.
16. What is the difference between this and super?
this refers to the current object (for example this.name = name). super refers to the parent class part of the object: super.method() calls the parent's version and super(...) calls the parent constructor, which must be the first line.
17. Why must you override hashCode() when you override equals()?
Hash-based collections such as HashMap and HashSet first use hashCode() to find the bucket, then equals() inside it. If two equal objects return different hash codes, they land in different buckets and the collection treats them as different, so lookups fail and duplicates appear.
Exceptions
18. What is the difference between checked and unchecked exceptions?
Checked exceptions (like IOException) must be caught or declared with throws; the compiler checks this. Unchecked exceptions extend RuntimeException (like NullPointerException) and usually mean a bug in the code; the compiler does not force you to handle them.
19. What is the difference between throw and throws?
throw actually throws one exception object: throw new IllegalArgumentException("age < 0"). throws in a method signature declares which checked exceptions the method may pass to its caller.
20. Does finally run if the try block returns?
Yes. finally runs after the try (or catch) block whether it finishes normally, returns or throws. It is skipped only if the JVM stops, for example with System.exit().
public class FinallyDemo {
static int value() {
try {
return 1;
} finally {
System.out.println("finally runs");
}
}
public static void main(String[] args) {
System.out.println(value());
}
}Output
finally runs 1
21. What is try-with-resources?
A try (...) block that opens resources such as files or database connections and closes them automatically at the end, even if an exception is thrown. The resource must implement AutoCloseable.
Collections
22. What is the difference between ArrayList and LinkedList?
ArrayList is backed by an array: reading by index is fast (O(1)), inserting in the middle is slow because elements shift. LinkedList is a chain of nodes: adding or removing at the ends is fast, but reaching an index means walking the list. In practice ArrayList is the default choice.
23. How does HashMap work internally?
It keeps an array of buckets. put computes the key's hashCode(), picks a bucket from it and stores the entry there; keys that land in the same bucket are kept in a small list (turned into a balanced tree when it grows long). get repeats the same steps and uses equals() to find the exact key. When the map gets too full (default load factor 0.75), it doubles the array and redistributes the entries.
24. What is the difference between HashMap, LinkedHashMap and TreeMap?
HashMap has no order and O(1) average operations. LinkedHashMap keeps insertion order. TreeMap keeps keys sorted and takes O(log n). See the full comparison in the guide linked below.
25. What is the difference between HashSet and TreeSet?
Both store unique elements. HashSet is unordered and O(1) on average; TreeSet keeps elements sorted and is O(log n). HashSet uses hashCode()/equals(); TreeSet uses compareTo() or a Comparator.
26. What is the difference between Comparable and Comparator?
Comparable defines the natural order inside the class itself with compareTo() (one order per class). Comparator is a separate object with compare(), so you can have many orders, such as by name or by salary, without changing the class.
27. What is a ConcurrentModificationException?
It is thrown when you change a collection (for example list.remove(x)) while looping over it with a for-each loop. Remove through the iterator (iterator.remove()) or use removeIf() instead.
Java 8 and modern Java
28. What is a lambda expression?
A short way to write an implementation of a functional interface (an interface with one abstract method). (a, b) -> a + b is a lambda; it removes the boilerplate of an anonymous class.
29. What is the Stream API?
A way to process collections as a pipeline: a source, then intermediate operations such as filter and map (lazy), then a terminal operation such as collect, count or forEach that produces the result. Streams do not change the original collection.
import java.util.List;
import java.util.stream.Collectors;
public class StreamDemo {
public static void main(String[] args) {
List<Integer> marks = List.of(45, 82, 67, 91, 38, 74);
List<Integer> passed = marks.stream()
.filter(m -> m >= 50)
.sorted()
.collect(Collectors.toList());
System.out.println(passed);
System.out.println(marks.stream().mapToInt(Integer::intValue).max().getAsInt());
}
}Output
[67, 74, 82, 91] 91
30. What is Optional and why use it?
Optional<T> is a box that either holds a value or is empty. Returning Optional instead of null makes "no result" visible in the method's type, so the caller has to handle it, for example with orElse("guest").
31. What is the difference between map() and flatMap() in streams?
map() turns each element into exactly one new element. flatMap() turns each element into a stream and joins all of them into one flat stream, for example a list of sentences into one stream of words.
Memory and threads
32. What is the difference between stack and heap memory?
Each thread has its own stack holding method calls and local variables; it is freed automatically when a method returns. Objects live on the shared heap, and the garbage collector frees them when nothing refers to them any more.
33. What is garbage collection?
The JVM automatically finds objects that can no longer be reached from your program and frees their memory. You cannot force it; System.gc() is only a request.
34. What is the difference between start() and run() on a thread?
start() creates a new thread, which then calls run(). Calling run() directly just runs the method on the current thread like any other method call; no new thread is created.
35. What do synchronized and volatile do?
synchronized lets only one thread at a time run a block or method on the same lock, which prevents race conditions. volatile makes every read and write of a variable go to main memory so all threads see the latest value, but it does not make compound actions such as count++ safe.
Tips for the interview itself
- Start with a one-line answer, then add an example. Interviewers prefer clear over long.
- If you do not know, say how you would find out. Guessing confidently is worse than an honest answer.
- Expect follow-up questions on anything you mention. Only bring up topics you can explain.
- Practise writing small programs by hand or in a plain editor; many rounds do not give you an IDE.
Frequently asked questions
How many Java questions should a fresher prepare?
Know the 35 here well, with examples, rather than memorising hundreds of answers. Interviewers dig into a few topics; depth matters more than count.
Which Java topics are asked most in fresher interviews?
OOP concepts, strings, == versus equals(), exceptions, collections (especially HashMap) and Java 8 streams and lambdas, plus simple coding problems.
Do freshers need to know multithreading?
Know the basics: what a thread is, start() versus run(), race conditions and synchronized. Deeper concurrency questions are more common for experienced roles.
Learn it step by step
- JDK, JRE and JVM
- Compare Strings: equals() and compareTo()
- Build and change text with StringBuilder
- Overloading vs overriding
- Abstract class or interface? How to choose
- hashCode() and the equals/hashCode contract
- Checked and unchecked exceptions
- How HashMap works inside
- Heap versus stack
- start() versus run()
Practise this, step by step
Short lessons with quizzes, practice and interview questions, from your first program to job-ready.