Interview Q&A / Java
Java interview questions
Collections, the JVM, strings, exceptions and threads, the backbone of most campus placement rounds.
Prefer rapid revision? Practise Java short interview answers →
- Can a try block exist without a catch block in Java?
Yes, as long as it has either a finally block or resources in try-with-resources. A bare try with neither is a compile error.
BeginnerQuick answer1 min read - Does calling System.gc() force garbage collection in Java?
No. System.gc() is only a hint, and the JVM may ignore it. Even when it runs, it often triggers an expensive full collection, so production code should not call it.
BeginnerQuick answer1 min read - How do you create a custom exception in Java?
Extend Exception for a checked custom exception or RuntimeException for an unchecked one, and add constructors that pass the message and optionally a cause to the parent. Use it to express a business rule clearly.
BeginnerQuick answer1 min read - How does a HashSet avoid storing duplicates in Java?
A HashSet is backed by a HashMap and stores each element as a key. add() uses hashCode to find the bucket and equals to check for an existing equal element; if one exists the add returns false and nothing is stored.
BeginnerQuick answer1 min read - How many objects does new String("India") create in Java?
Up to two. The literal "India" goes into the string pool if it is not already there, and new String(...) always creates a separate object on the heap. So two objects the first time, and one if the pool already had the literal.
BeginnerQuick answer1 min read - Should you extend Thread or implement Runnable in Java?
Implement Runnable in most cases. It separates the task from the thread, leaves your class free to extend something else, and works with thread pools. Extending Thread only makes sense if you are changing the thread behaviour itself.
BeginnerQuick answer1 min read - What are the four access levels in Java and who can see each one?
private is visible only inside the class. Default (no keyword) adds the same package. protected adds subclasses in other packages. public is visible everywhere.
BeginnerQuick answer1 min read - What are the four pillars of object-oriented programming in Java?
Encapsulation hides data behind methods, abstraction exposes only what matters, inheritance reuses a parent class, and polymorphism lets one call behave differently depending on the actual object.
BeginnerQuick answer1 min read - What causes ConcurrentModificationException and how do you avoid it?
It is thrown when a collection is structurally modified while you iterate over it, for example calling list.remove() inside a for-each loop. Remove through the Iterator, use removeIf, or iterate over a copy.
BeginnerQuick answer1 min read - What does the transient keyword do in Java?
transient marks a field to be skipped during serialization. When the object is deserialized, that field gets its default value (null, 0 or false), which is useful for passwords, caches and values that can be recomputed.
BeginnerQuick answer1 min read - What happens if you call run() instead of start() on a Java thread?
start() creates a new thread of execution and calls run() on it. Calling run() directly is an ordinary method call on the current thread, so no concurrency happens. Calling start() twice throws IllegalThreadStateException.
BeginnerQuick answer1 min read - What is a functional interface in Java and which built-in ones should you know?
A functional interface has exactly one abstract method, so a lambda can implement it. Core ones are Predicate (test), Function (apply), Consumer (accept) and Supplier (get). @FunctionalInterface makes the compiler check the rule.
BeginnerQuick answer1 min read - What is a lambda expression in Java and where can you use it?
A lambda is a short anonymous function written as (parameters) -> body. It can be used wherever a functional interface, an interface with exactly one abstract method, is expected, such as Runnable, Comparator or Predicate.
BeginnerQuick answer1 min read - What is a method reference in Java and when would you use it instead of a lambda?
A method reference is a shorthand like String::length for a lambda that only calls one existing method. It makes code shorter and clearer when the lambda adds nothing beyond that call.
BeginnerQuick answer1 min read - What is constructor chaining in Java and are constructors inherited?
Constructors are not inherited. Every constructor starts by calling another one, either this(...) in the same class or super(...) in the parent, and Java inserts super() automatically if you write neither.
BeginnerQuick answer1 min read - What is the difference between Comparable and Comparator in Java?
Comparable defines one natural order inside the class itself through compareTo. Comparator is a separate object with a compare method, so you can define many different orderings without changing the class.
BeginnerQuick answer1 min read - What is the difference between encapsulation and abstraction in Java?
Abstraction hides complexity by showing only what a user needs, usually through interfaces or abstract classes. Encapsulation hides data by keeping fields private and exposing controlled methods. One is about design, the other about protection.
BeginnerQuick answer1 min read - What is the difference between Error and Exception in Java?
Both extend Throwable. An Exception represents a problem a program can reasonably catch and handle, while an Error such as OutOfMemoryError signals a serious JVM-level failure that applications normally should not try to recover from.
BeginnerQuick answer1 min read - What is the difference between HashMap, LinkedHashMap and TreeMap?
HashMap has no guaranteed order and gives O(1) operations. LinkedHashMap keeps insertion order, also in O(1). TreeMap keeps keys sorted and costs O(log n). Pick by the order you need.
BeginnerQuick answer1 min read - What is the difference between heap and stack memory in Java?
The stack holds method call frames with local primitives and references, and each thread has its own. The heap holds all objects and is shared by every thread and cleaned by the garbage collector.
BeginnerQuick answer1 min read - What is the difference between method overloading and method overriding in Java?
Overloading is several methods with the same name but different parameters in one class, resolved at compile time. Overriding is a subclass replacing a parent method with the same signature, resolved at runtime.
BeginnerQuick answer1 min read - What is the difference between OutOfMemoryError and StackOverflowError?
StackOverflowError happens when a thread call stack is exhausted, usually by endless recursion. OutOfMemoryError happens when the heap, or another memory area, cannot supply memory even after garbage collection.
BeginnerQuick answer1 min read - What is the difference between this and super in Java?
this refers to the current object, and this(...) calls another constructor of the same class. super refers to the parent class part of the object, and super(...) calls a parent constructor.
BeginnerQuick answer1 min read - What is the difference between throw and throws in Java?
throw is a statement that actually raises one exception object at that moment. throws is part of a method signature that warns callers which checked exceptions the method might pass on.
BeginnerQuick answer1 min read - What is try-with-resources in Java and why is it better than try-finally?
It declares AutoCloseable resources in the try parentheses and closes them automatically, in reverse order, even when an exception occurs. It is shorter than try-finally and keeps the original exception when close() also fails.
BeginnerQuick answer1 min read - When does an object become eligible for garbage collection in Java?
An object is eligible once no live thread can reach it through any chain of references from the GC roots, such as local variables, static fields and active threads. Setting a reference to null or leaving its scope can make it unreachable.
BeginnerQuick answer1 min read - Why can a static method not use non-static variables or this in Java?
A static method belongs to the class and can run without any object, so there is no this and no instance to read fields from. To use an instance member it must be given an object explicitly.
BeginnerQuick answer1 min read - Why is the main method public static void in Java?
public so the JVM can call it from outside, static so it can run without creating an object, void because the JVM does not use a return value, and String[] args carries the command-line arguments.
BeginnerQuick answer1 min read - Why is the String class immutable in Java?
Once created, a String cannot change. This makes the string pool safe to share, lets the hash code be cached for fast HashMap use, keeps strings thread-safe, and stops callers from altering values used for security, such as file paths or URLs.
BeginnerQuick answer1 min read - Why is using + to join strings inside a loop slow in Java?
Each + creates a brand new String and copies all earlier characters, so n appends cost about O(n squared) in total. A StringBuilder keeps one growing buffer and appends in amortised O(1), making the whole loop O(n).
BeginnerQuick answer1 min read