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 →
- 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