Java Interview Questions for Freshers (2026): 40 Questions with Clear Answers
- Home
- Blog
- Full Stack & Programming
- Java Interview Questions for Freshers (2026): 40 Questions with Clear Answers
Short answer: fresher Java interviews concentrate on core Java: JDK vs JRE vs JVM, OOP concepts with examples, why strings are immutable, == vs equals(), exception handling, the collections framework (ArrayList vs LinkedList, HashMap internals), basic multithreading, and Java 8 features such as lambdas and streams. Service companies add aptitude and simple coding problems; product companies add data structures and algorithms. For Java full stack roles, expect a few questions on JDBC, Spring Boot and REST APIs.
Not sure what to study first? Read core Java vs advanced Java, and if you are choosing a stack, compare MERN vs Java full stack.
Java basics
1. What are the main features of Java?
Object-oriented, platform independent (“write once, run anywhere”), strongly and statically typed, with automatic memory management (garbage collection), a rich standard library, built-in multithreading and strong backward compatibility.
2. What is the difference between JDK, JRE and JVM?
| What it is | Contains | |
|---|---|---|
| JVM | Java Virtual Machine that runs bytecode | Class loader, bytecode verifier, interpreter and JIT compiler, garbage collector |
| JRE | Runtime environment to run Java programs | JVM plus core libraries |
| JDK | Development kit to write and build Java programs | JRE plus tools such as javac, java, jar and javadoc |
Since Java 11, Oracle and most vendors distribute the JDK only, so in practice you install a JDK.
3. Why is Java platform independent?
javac compiles source code into bytecode, not machine code. Any operating system with a JVM can run that bytecode, and the JIT compiler turns hot code paths into native machine code at run time.
4. Which Java version should a fresher know?
Know Java 8 features well, because many projects still use them, and be aware of the newer long-term support releases: Java 17, 21 and 25. Records, text blocks, switch expressions and virtual threads (Java 21) are good modern features to mention.
5. Why is main declared public static void main(String[] args)?
public so the JVM can call it, static so it runs without creating an object, void because it returns nothing, and String[] args to receive command-line arguments.
6. What are primitive and reference types?
Java has eight primitives: byte, short, int, long, float, double, char and boolean. Everything else is a reference type that points to an object. Wrapper classes (Integer, Double) box primitives so they can be used in collections.
7. Is Java pass by value or pass by reference?
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.
Object-oriented programming
8. Explain the four OOP pillars with examples.
Encapsulation: private fields with getters and setters, as in a BankAccount that validates deposits. Inheritance: SavingsAccount extends BankAccount. Polymorphism: a Payment reference calling pay() on UpiPayment or CardPayment. Abstraction: an interface or abstract class that defines what to do, not how.
9. What is the difference between method overloading and overriding?
Overloading means the same method name with different parameters in the same class, resolved at compile time. Overriding means a subclass provides its own implementation of a parent method with the same signature, resolved at run time.
10. What is the difference between an abstract class and an interface?
An abstract class can have state (fields), constructors and both abstract and concrete methods, and a class can extend only one. An interface defines a contract; since Java 8 it can have default and static methods, and a class can implement many interfaces. Use interfaces for capabilities and abstract classes for shared base behaviour.
11. Why does Java not support multiple inheritance of classes?
To avoid the “diamond problem”, where two parents provide conflicting implementations. Java allows multiple inheritance of type through interfaces instead.
12. What do this and super mean?
this refers to the current object and can call another constructor in the same class. super refers to the parent class and calls its constructor or methods.
13. What are the access modifiers?
private (same class), default/package-private (same package), protected (same package plus subclasses) and public (everywhere).
14. What does final do?
A final variable cannot be reassigned, a final method cannot be overridden, and a final class cannot be extended.
15. What is the difference between static and instance members?
Static members belong to the class and are shared by all objects. Instance members belong to each object. Static methods cannot use this or access instance fields directly.
Strings
16. Why are strings immutable in Java?
For security (strings are used for file paths, URLs and class names), thread safety, caching of hash codes and the string pool, which lets identical literals share one object.
17. What is the difference between == and equals()?
== compares references (are these the same object?). equals() compares content when the class overrides it, as String does. Always compare strings with equals().
18. 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 synchronized (thread-safe) but slower. Use StringBuilder when building strings in loops.
19. Why must you override hashCode() when you override equals()?
Hash-based collections such as HashMap and HashSet use hashCode() to find the bucket and equals() to compare within it. Equal objects must have equal hash codes, or lookups will fail.
Exception handling
20. What is the difference between checked and unchecked exceptions?
Checked exceptions (such as IOException and SQLException) must be handled or declared with throws. Unchecked exceptions extend RuntimeException (such as NullPointerException and ArrayIndexOutOfBoundsException) and usually signal programming errors.
21. What is the difference between throw and throws?
throw actually throws an exception object inside a method. throws in a method signature declares which checked exceptions the method may pass to its caller.
22. What is try-with-resources?
try (BufferedReader reader = new BufferedReader(new FileReader("data.txt"))) {
System.out.println(reader.readLine());
} catch (IOException e) {
e.printStackTrace();
} // reader is closed automatically
23. What is the difference between final, finally and finalize?
final is a modifier, finally is a block that runs after try/catch whether or not an exception occurred, and finalize() was a cleanup hook called by the garbage collector. It is deprecated and should not be used.
Collections framework
24. What is the difference between ArrayList and LinkedList?
ArrayList is backed by a resizable array, so access by index is fast but inserting in the middle is slow. LinkedList is a doubly linked list, so insertion and removal at the ends are fast but access by index is slow. ArrayList is the default choice in most code.
25. What is the difference between List, Set and Map?
A List is ordered and allows duplicates, a Set holds unique elements, and a Map stores key–value pairs with unique keys. Map is part of the collections framework but does not extend the Collection interface.
26. How does HashMap work internally?
HashMap stores entries in an array of buckets. It computes the key’s hashCode(), maps it to a bucket and stores the entry there. Collisions are kept in a linked list, which Java 8 turns into a balanced tree when a bucket grows large. When the map passes its load factor (0.75 by default), it resizes and rehashes.
27. HashMap vs Hashtable vs ConcurrentHashMap?
HashMap is not synchronized and allows one null key. Hashtable is a legacy, fully synchronized class with no null keys or values. ConcurrentHashMap is the modern thread-safe choice with much better concurrency.
28. HashSet vs LinkedHashSet vs TreeSet?
HashSet has no ordering, LinkedHashSet keeps insertion order, and TreeSet keeps elements sorted.
29. What is the difference between Comparable and Comparator?
Comparable defines a class’s natural order through compareTo() inside the class. Comparator defines external, custom orders, for example students.sort(Comparator.comparing(Student::getMarks)).
30. What is a fail-fast iterator?
An iterator that throws ConcurrentModificationException if the collection is structurally modified while iterating, except through the iterator’s own remove().
Multithreading
31. How do you create a thread?
Extend Thread, or better, implement Runnable or Callable and submit it to an ExecutorService. Java 21 also adds lightweight virtual threads for high-concurrency applications.
32. What is synchronization?
Synchronization ensures only one thread at a time runs a critical section, preventing race conditions on shared data. Use synchronized methods or blocks, or classes from java.util.concurrent.
33. What is a deadlock?
Two or more threads waiting forever for locks held by each other. Avoid it by acquiring locks in a consistent order, holding them briefly and using timeouts.
Java 8 and modern Java
34. What are lambda expressions and functional interfaces?
A functional interface has exactly one abstract method, such as Runnable, Comparator or Predicate. A lambda is a concise implementation of it: (a, b) -> a + b.
35. What is the Stream API?
List<String> toppers = students.stream()
.filter(s -> s.getMarks() >= 75)
.map(Student::getName)
.sorted()
.toList();
Streams process collections declaratively with intermediate operations (filter, map, sorted) and a terminal operation (collect, toList, count).
36. What is Optional?
A container that may or may not hold a value, used as a return type to make “no result” explicit and reduce NullPointerExceptions: repo.findById(id).orElseThrow().
Java full stack basics
37. What is JDBC?
Java Database Connectivity is the API for connecting to relational databases. Use PreparedStatement with parameters rather than string concatenation to prevent SQL injection and improve performance.
38. What is Spring Boot and why is it used?
Spring Boot builds on the Spring framework with auto-configuration, starter dependencies and an embedded server, so you can create production-ready REST APIs and web applications quickly. Spring Data JPA with Hibernate handles database access.
Coding questions
39. Reverse a string without using reverse().
static String reverse(String s) {
StringBuilder sb = new StringBuilder();
for (int i = s.length() - 1; i >= 0; i--) {
sb.append(s.charAt(i));
}
return sb.toString();
}
40. Count the occurrences of each character.
Map<Character, Integer> counts = new LinkedHashMap<>();
for (char c : "programming".toCharArray()) {
counts.merge(c, 1, Integer::sum);
}
System.out.println(counts); // {p=1, r=2, o=1, g=2, a=1, m=2, i=1, n=1}
How to prepare
- Write small programs for every concept above. Interviewers often ask you to write code on paper or in a plain editor.
- Practise common string, array and collection programs: palindromes, duplicates, frequency counts, second largest, anagram checks and Fibonacci.
- Prepare one project you can explain end to end, ideally a Spring Boot REST API with a database.
- Revise SQL basics, because most Java developer roles include database questions. Our SQL interview questions cover the core queries.
- Read our guide to how much DSA you need for placements and the tech interview preparation guide.
Learn Java at TryCatch Classes
TryCatch Classes’ Core Java Training covers JDK, JVM and JRE setup, data types, control flow, arrays, strings, methods and recursion, OOP, exception handling, collections, multithreading, lambdas and functional interfaces, and JVM internals. Advanced Java Training adds JDBC, Maven, servlets, sessions and filters, Hibernate and Spring Boot REST APIs, and Java Full Stack combines Java with front-end development. Learn at our Borivali West classroom or live online, with a 100% placement guarantee.
A note from Mehul Prajapati, Founder, TryCatch Classes
I have spent 18+ years in IT and training and have personally mentored 12,000+ students. If you are planning your next step in Java and want a second opinion on your learning path, I am happy to help.
“The technology you learn today may change tomorrow, but your ability to learn will always be your biggest strength. Stay curious, keep upgrading yourself, and never stop growing.”
Message me on WhatsApp at +91 99301 12627 and tell me which blog you read. I would love to hear from you.
Planning your path? Follow the Java developer roadmap.
Frequently asked questions
Which Java topics are most important for freshers?
OOP with examples, strings, exception handling, collections (especially HashMap), Java 8 lambdas and streams, and basic multithreading. Add JDBC and Spring Boot for full stack roles.
Is Java still a good choice for freshers in 2026?
Yes. Java remains widely used in banking, enterprise software and Android, and Java full stack and Spring Boot roles are common in Indian job listings.
Do service companies ask DSA in Java interviews?
Usually basic problems on strings, arrays and collections. Product companies go deeper into data structures and algorithms.
Should I learn Java 8 or the latest version?
Learn modern Java (17 or newer), but make sure you know Java 8 features thoroughly, because many interview questions and existing projects still revolve around them.
Cover image: photo by Juanjo Jaramillo on Unsplash.
Keep reading
Full Stack & ProgrammingPython Developer Roadmap for Freshers (2026): Basics to a Job-Ready PathA step-by-step Python developer roadmap for freshers: the basics, functions and data structures, OOP, files and errors, the package ecosystem, then choosing a direction (web, data/AI…Full Stack & ProgrammingJava Developer Roadmap for Freshers (2026): Core Java to Spring BootFull Stack & ProgrammingGit and GitHub for Beginners (2026): Commands, Workflow and First Steps← Previous articlePython Interview Questions for Freshers (2026): 35 Questions with Clear AnswersNext article →Power BI Interview Questions for Freshers (2026): 35 Questions with Answers
