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 →
- 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 - Write a Java method that reverses the order of words in a sentence.
Trim the text, split on one or more spaces, then join the pieces from last to first with a single space. It takes O(n) time and O(n) space for the word array and result.
BeginnerQuick answerCoding1 min read - Write a Java method to check whether a string is a palindrome, ignoring case and non-letters.
Use two pointers from both ends, skip anything that is not a letter or digit, compare lowercase characters, and move inward. It runs in O(n) time with O(1) extra space.
BeginnerQuick answerCoding1 min read - Write a Java method to check whether two lowercase strings are anagrams.
If the lengths differ the answer is no. Otherwise count each letter of the first string up and each letter of the second down in an int[26], and the strings are anagrams if every count ends at zero. O(n) time, O(1) space.
BeginnerQuick answerCoding1 min read - Write a Java method to remove duplicates from a list while keeping the original order.
Put the elements into a LinkedHashSet, which drops repeats and remembers first-seen order, then copy it back into a list. It takes O(n) time and O(n) space.
BeginnerQuick answerCoding1 min read - Can static, private and final methods be overridden in Java?
No. Final methods are forbidden from overriding, private methods are invisible to subclasses, and static methods belong to the class, so a same-named subclass method only hides the parent one instead of overriding it.
IntermediateQuick answer1 min read - How can a memory leak happen in Java even with garbage collection?
A leak happens when objects are no longer needed but are still reachable, so GC cannot free them. Common causes are growing static collections, unremoved listeners, unclosed resources and keys in a map that are never removed.
IntermediateQuick answer1 min read - How does a deadlock happen in Java and how can you avoid it?
A deadlock occurs when threads each hold one lock and wait forever for a lock the other holds. Avoid it by always acquiring locks in the same order, holding fewer locks, or using tryLock with a timeout.
IntermediateQuick answer1 min read - How does PriorityQueue order its elements in Java?
PriorityQueue is a binary min-heap, so poll() always returns the smallest element by natural order or a Comparator. Add and poll cost O(log n), peek is O(1), and iterating it does not give sorted order.
IntermediateQuick answer1 min read - In what order do static blocks, instance blocks and constructors run in Java?
A static block runs once when the class is first loaded. For every new object, instance initialiser blocks and field initialisers run first, in source order, and then the constructor body.
IntermediateQuick answer1 min read - In what order should catch blocks be written, and what is multi-catch in Java?
Catch blocks are checked top to bottom, so subclasses must come before their parents or the code will not compile. Multi-catch uses a pipe to handle several unrelated exceptions in one block.
IntermediateQuick answer1 min read - What are the young and old generations in the Java heap?
New objects start in the young generation, which is collected often and cheaply because most objects die quickly. Objects that survive several collections are promoted to the old generation, which is collected less often.
IntermediateQuick answer1 min read - What does a Java method return when both try and finally contain a return?
The finally block runs before the method actually returns, and a return inside finally overrides the earlier one, so the finally value wins. If finally only changes a variable, a primitive value already chosen for return is not affected.
IntermediateQuick answer1 min read - What does the intern() method of String do?
intern() returns the pooled copy of a string. If the pool already holds an equal string it returns that one, otherwise it adds this string to the pool and returns it, so interned strings with equal text compare equal with ==.
IntermediateQuick answer1 min read - What does the volatile keyword do in Java, and does it make count++ safe?
volatile guarantees that a write by one thread is immediately visible to other threads and prevents certain reordering. It does not make compound actions like count++ atomic, so a counter still needs synchronized or AtomicInteger.
IntermediateQuick answer1 min read - What does this Java code print when a parent reference holds a child object?
Methods are looked up on the real object at runtime, so the child version runs. Fields are looked up on the reference type at compile time, so the parent field is read. Fields are never polymorphic.
IntermediateQuick answer1 min read - What is a blank final variable in Java and how do you initialise it?
A blank final is a final field declared without a value. It must be assigned exactly once, in every constructor for an instance field or in a static block for a static one, otherwise the code does not compile.
IntermediateQuick answer1 min read - What is a TreeMap and how does it keep its keys sorted?
TreeMap stores entries in a red-black tree, a self-balancing binary search tree, ordered by the keys natural order or a supplied Comparator. get, put and remove take O(log n), and it offers range methods like firstKey and floorKey.
IntermediateQuick answer1 min read - What is exception chaining in Java and why keep the cause?
Exception chaining wraps a low-level exception inside a higher-level one using the cause argument, so callers get a meaningful message and the stack trace still shows the original failure through getCause().
IntermediateQuick answer1 min read - What is Metaspace and how is it different from PermGen?
Metaspace stores class metadata and, since Java 8, replaced PermGen. PermGen was a fixed-size part of the heap, while Metaspace uses native memory and grows as needed unless MaxMetaspaceSize is set.
IntermediateQuick answer1 min read - What is the difference between a static nested class and an inner class in Java?
An inner (non-static) class holds a hidden reference to an instance of its outer class and can use its members. A static nested class has no such link, so it can be created without an outer object, like an ordinary top-level class placed inside another for organisation.
IntermediateQuick answer1 min read - What is the difference between a synchronized method and a synchronized block in Java?
A synchronized method locks the whole method on this (or the Class for static methods). A synchronized block locks only the lines inside it, on any object you pick, so threads wait less and you can use separate locks for separate data.
IntermediateQuick answer1 min read - What is the difference between map and flatMap in Java streams?
map transforms each element into exactly one new element. flatMap transforms each element into a stream and then merges all those streams into one flat stream, which is how you unpack lists inside lists.
IntermediateQuick answer1 min read