The interviewer asks how a HashMap works. You say "key-value pairs, O(1) lookup" and stop. They wait a second, then ask, "What happens when two keys land in the same bucket?" You know you read about this, but you cannot find it. Collision handling in data structures comes up in almost every set of java interview questions for freshers, and it is exactly the kind of follow-up this guide prepares you for.
That pause is where most fresher Java interviews are decided. The first question checks whether you have heard of something. The follow-up checks whether you understand it, and it comes almost every time.
The short answer
Java interview questions for freshers often focus on core concepts like the JVM, OOP principles, and collections. Understanding how these elements work together is crucial for success in interviews. Prepare by practicing common questions and their follow-ups to build confidence.
The short answer
Core Java interview questions for freshers come from a small, predictable pool. The ones actually asked in a Java interview cover the JVM, OOP, Strings, equals and hashCode, keywords like final and static, collections, exceptions, generics, Java 8 features, basic threading and garbage collection. For each question below you get a model answer that explains why Java works that way, and the follow-up you are most likely to hear next. Learn the reasoning, not the wording, and say each answer out loud at least once.
Key takeaways
To succeed in Java interviews, focus on understanding key concepts rather than just memorizing answers. Familiarize yourself with core topics such as the JVM, OOP principles, and collections, as these are frequently covered in interviews. Practicing common questions and their follow-ups will help you articulate your knowledge effectively.
Preparing for Java Interviews
To excel in Java interviews, it's essential to not only memorize answers but also understand the underlying concepts. Engage in mock interviews with peers or use online platforms to simulate the interview experience. This will help you articulate your thoughts clearly under pressure.
Additionally, focus on coding exercises that reinforce your understanding of Java's syntax and features. Websites like LeetCode and GeeksforGeeks offer a wealth of practice problems tailored for Java developers.
- Understanding how a HashMap handles collisions is crucial for Java interviews.
- The JVM, JRE, and JDK have distinct roles in running Java applications.
- OOP principles like encapsulation, inheritance, and polymorphism are fundamental in Java.
- Strings in Java are immutable, which has implications for performance and security.
- Knowing the differences between collections like ArrayList and LinkedList can impact performance.
For the wider plan around this list, see our interview preparation guide for freshers. This article is the Java question bank.
The JVM and the platform
- What is the difference between the JDK, JRE and JVM?
The JVM runs bytecode: it loads classes, verifies them, interprets them and compiles hot code to machine code with the JIT compiler. The JRE is the JVM plus the standard class libraries, which is what you need to run a program. The JDK is the JRE plus development tools such as javac, jar and jdb, which is what you need to write one.
"Do you still download a separate JRE?" Not from Oracle since Java 11. You install a JDK, and if you need a slim runtime for deployment you build one with jlink.
- Why is Java called platform independent?
Because javac compiles your code to bytecode, not to machine code for one processor. Any machine with a JVM can run that same.class file. The JVM itself is platform specific, and that is the design: the platform dependence lives in the JVM so your code does not have to carry it.
"Is Java slow because it is interpreted?" Not for long-running code. The JIT compiler watches which methods run often and compiles them to native code, so a warmed-up Java program
runs close to compiled speed.
OOP in Java
- What are the four pillars of OOP, in Java terms?
Encapsulation is private fields with methods that control how they change. Abstractio class that lets callers use something without knowing how it works. Inheritance isextends, which reuses behaviour. Polymorphism is one call doing the right thing for different types, such as shape.area() working for both a Circle and a Square.
- What is the difference between method overloading and overriding?
Overloading is several methods with the same name and different parameter lists in one class, and the compiler picks which one to call at compile time. Overriding is a subclass replacing a parent's method with the same signature, and the JVM picks which version runs at runtime baseds why overriding is runtime polymorphism and overloading is compile-time.
"Can you override a static method?" No. A static method with the sades the parent's one, and which runs depends on the reference type, not the object.
- Interface or abstract class: when would you pick each?
An abstract class can hold state (instance fields) and constructors, and a class can defines a capability, and a class can implement many. Since Java 8, interfaces canhave default and static methods, and since Java 9 private methods, so the old "interfaces have no method bodies" answer is out of date. Pick an abstract class when related classes share state and code.
Pick an interface when unrelated classes need the same contract, like Comparable.
- Explain the access modifiers.
private is visible only inside the class. No modifier (package-private) is visible inted adds subclasses in other packages. public is visible everywhere. Default to thenarrowest that works.
Strings
- Why are Strings immutable in Java?
There are four reasons, and they support each other. Immutable strings can be safely shared from the string pool. They are safe to pass between threads without locking. Their hash code can be cached,
which makes them fast HashMap keys. And security-sensitive values like file paths cand.
- What is the String pool, and what does == compare?
String literals are stored once in a pool and reused, so "java" == "java" is always tidentical literals refer to the same pooled object. new String("java") forces a newobject on the heap, so == against the literal is false. == compares references and equals() compares contents, so always use equals() for strings. The pool has lived in the main heap since Java 7.
- String, StringBuilder or StringBuffer?
Because String is immutable, concatenating in a loop creates a new object every iteration. StringBuilder is a mutable buffer you append to, so use it to build strings in a loop. StringBuffer does the
same but synchronizes every method, which costs speed and is rarely needed, so String
Core keywords and object basics
- What is the contract between equals() and hashCode()?
If two objects are equal by equals(), they must return the same hashCode(). The reverontract and hash-based collections stop working: override equals() without hashCode(),and two "equal" objects can go into different buckets, so set.contains(x) returns false for something you just added.
"Should a HashMap key be mutable?" No. If a field used in hashCode() changes after insertion, the entry sits in the wrong bucket and cannot be found.
- What is the difference between final, finally and finalize?
final stops change: a final variable cannot be reassigned, a final method cannot be overridden, and a final class cannot be extended. finally is the block after try that runs whether or not an
exception was thrown, used for cleanup. finalize() was a method the garbage collector an object. It was deprecated in Java 9 and deprecated for removal in Java 18, becausenothing when, or whether, it ran. Use try-with-resources instead.
"Does a final list mean the list cannot change?" No. The reference cannot be reassigned, but you can still add to the list.
- What does static mean?
A static member belongs to the class, not to any object. A static field has one copy shared by every instance. A static method can be called without an object, which is why it cannot use this or instance fields directly. main is static because the JVM calls it before any object e
Collections
- ArrayList or LinkedList?
ArrayList is backed by an array, so get(i) is O(1) and iteration is cache-friendly. A O(1), while inserting in the middle shifts elements. LinkedList is a doubly linkedlist, so get(i) is O(n). People often say it is faster for insertion in the middle, but you have to walk to that position first, so ArrayList wins in most real code.
- How does a HashMap work internally?
It holds an array of buckets. On put, it calls the key's hashCode(), mixes the high bits into the low bits, and uses the result to pick a bucket index. If the bucket is empty, the entry goes in. If not, it walks the entries there, using equals() to find a matching key to replace, ormber of entries passes capacity times the load factor (16 and 0.75 by default), thearray doubles and entries are redistributed.
"What happens with lots of collisions?" Since Java 8, a bucket that grows past eight entries is converted from a linked list into a balanced tree (once the table has at least 64 buckets), so worst-case lookup in that bucket drops from O(n) to O(log n).
- How does a HashSet ensure uniqueness?
A HashSet is backed by a HashMap. Each element is stored as a key with a dummy value, map's hashCode() and equals() logic. That is also why a broken equals/hashCodecontract lets duplicates in.
- Why use ConcurrentHashMap instead of a synchronized HashMap?
Collections.synchronizedMap locks the whole map for every operation, so threads queue up. ConcurrentHashMap lets reads proceed without locking. Since Java 8 it writes to empty buckets with compare-and-swap and locks only the single bucket being changed. It also rejects nulla concurrent map a null from get would be ambiguous.
If collections feel shaky, go one level down: the data structures you must know covert on.
Exceptions and generics
- Checked vs unchecked exceptions?
Checked exceptions (subclasses of Exception but not RuntimeException, like IOExceptio with throws. The compiler enforces this because they describe failures a caller canreasonably recover from. Unchecked exceptions (RuntimeException and its subclasses, like NullPointerException) usually signal a bug, so forcing every caller to handle them would add noise. Error, likeOutOfMemoryError, is for problems the application should not try to catch.
"What is try-with-resources?" Added in Java 7, it automatically cloAutoCloseable when the block ends, even if an exception is thrown.
- Why use generics, and what is type erasure?
Generics let the compiler check types, so List<String> will not accept an Integer andeading. Type erasure means this checking happens only at compile time: at runtime aList<String> is just a List. That is why you cannot write new T() or check instanceof List<String>.
Java 8 features
- What is a lambda, and what is a functional interface?
A functional interface has exactly one abstract method, like Runnable or Comparator. A lambda is a short way to provide that one method without writing an anonymous class: list.sort((a, b) -> a.length() - b.length()).
- What are streams, and how are they different from collections?
A collection stores data. A stream describes a pipeline of operations over data: filtation like collect or count. Intermediate operations are lazy, so nothing runs untilthe terminal operation, and a stream can be consumed only once.
"What is the difference between map and flatMap?" map turns each element into one result. flatMap turns each element into a stream and flattens them into one, which is what you want for a list of lists.
- What is Optional for?
Optional puts "this might be missing" into a method's return type, so the caller has f hitting a NullPointerException later. Use orElse, orElseGet or map rather thancalling get() without checking. It is meant for return values, not for fields or method parameters.
Threads and memory
- Should you extend Thread or implement Runnable?
Implement Runnable, or Callable if you need a result. Java has single inheritance, so extending Thread uses up your one parent class, and it mixes the task with the mechanism that runs it. In real codyou submit tasks to an ExecutorService. Since Java 21, virtual threads make it cheap tasks concurrently.
"What is the difference between start() and run()?" start() creates run(). Calling run() directly just executes it on the current thread.
- What does synchronized do?
It makes a thread acquire an object's monitor lock before entering a method or block, runs code guarded by that lock. It also makes changes inside the block visible to thenext thread that takes the lock. A synchronized instance method locks this, and a synchronized static method locks the class object.
- What does volatile do, and is it enough for a counter?
volatile guarantees that a write to the variable happens-before every later read of it by another thread, so readers always see the latest value, and accesses are not reordered around it. It does not make compound operations atomic. count++ is a read, an add and a write, so two threadse AtomicInteger or synchronized for counters, and volatile for simple flags like arunning boolean.
- How does garbage collection work, at a basic level?
Objects live on the heap. The garbage collector finds objects that can no longer be reached from any live reference (local variables, static fields, active threads) and reclaims their memory. Most collectors are generational, because most objects die young. New objects go in the yoected often and cheaply, and survivors are promoted to the old generation. G1 has beenthe default collector on server-class machines since Java 9. You can request a collection with System.gc(), but the JVM is free to ignore it.
"Can you get a memory leak in Java?" Yes. If you keep references you no longer need, such as entries in a static map that is never cleared, the collector cannot reclaim them.
How to practise these
Common Mistakes to Avoid
During interviews, candidates often make the mistake of providing overly technical answers without context. Always aim to explain your thought process clearly and relate it back to practical applications. This approach not only demonstrates your knowledge but also your ability to communicate effectively.
Another common pitfall is neglecting to ask clarifying questions. If a question seems ambiguous, don't hesitate to seek clarification. This shows your analytical skills and ensures you fully understand what is being asked.
Reading these answers is easier than giving them when a follow-up catches you off guard. Why knowing the answer isn't enough covers that gap. For the questions you cannot answer at all, guessing is thworst option; how to handle a question you don't know covers what to do instead.
Practise in pairs: one person asks a question, then asks "why?" twice. If you are pre, the Python interview questions for freshers follow the same format.
To rehearse with someone who keeps asking, pick Java as your stack in a scored round e page. Sia, the AI interviewer, asks one question at a time, follows up on what youactually said, and gives you a written breakdown at the end. If you would rather practise with a person, book a live 40-minute Zoom interview with a working engineer. You get scored, written feedback on technical depth, problem solving, communication, behaviour and code quality.
For the coding round, read coding interview questions for freshers.
For more on this, read Top Node.js Interview Questions for Freshers.
You can rehearse this out loud in Java interview practice.
The official Java learning pages are the best place to check how a language feature actually behaves.
Additional Resources
For further study, consider exploring related topics in software development. Check out our posts on Java Coding Interview Questions: 25 Programs and How to Explain Each and C and C++ Interview Questions for Freshers. These resources will provide you with a broader understanding of programming concepts that may come up in interviews.