Interview Q&A / Java

INTERVIEW Q&A · 72 QUESTIONS

Java interview questions

Collections, the JVM, strings, exceptions and threads, the backbone of most campus placement rounds.

  1. 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
  2. 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
  3. 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
  4. 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
  5. 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
  6. 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
  7. 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
  8. 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
  9. 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
  10. 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
  11. 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
  12. 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
  13. 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
  14. 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
  15. 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
  16. 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
  17. 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
  18. 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
  19. 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
  20. 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
  21. 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
  22. 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
  23. What is the difference between orElse and orElseGet in Java Optional?

    orElse takes a ready value that is always evaluated, even when the Optional has a value. orElseGet takes a Supplier that runs only when the Optional is empty, so use it when the fallback is expensive or has side effects.

    IntermediateQuick answer1 min read
  24. What is the difference between Runnable and Callable, and what is a Future?

    Runnable.run returns nothing and cannot throw checked exceptions. Callable.call returns a value and may throw. Submitting a Callable to an ExecutorService gives a Future, a handle you use to fetch the result later.

    IntermediateQuick answer1 min read
  25. What is the difference between wait() and sleep() in Java?

    sleep() pauses the current thread for a time and keeps any lock it holds. wait() must be called inside a synchronized block, releases that lock, and pauses until notify or notifyAll is called or the timeout ends.

    IntermediateQuick answer1 min read
  26. When should you use composition instead of inheritance in Java?

    Use inheritance for a true is-a relationship and composition for has-a. Composition is usually safer because the classes stay loosely coupled and you can change the part at runtime, while inheritance ties the child tightly to the parent.

    IntermediateQuick answer1 min read
  27. Why does a Java stream do nothing until a terminal operation is called?

    Intermediate operations like filter and map only describe the pipeline. Work starts when a terminal operation such as collect, count or forEach is called, and elements then flow through the whole pipeline one at a time.

    IntermediateQuick answer1 min read
  28. Why does Java not allow a class to extend more than one class?

    To avoid the diamond problem, where two parents define the same method and the child cannot tell which one to inherit. Java allows multiple interfaces instead, and since Java 8 a conflicting default method must be resolved explicitly.

    IntermediateQuick answer1 min read
  29. Why is a char array recommended over String for storing passwords in Java?

    A String is immutable and may stay in memory until garbage collection, so it cannot be wiped. A char array can be overwritten with blanks right after use, which shrinks the time a password sits in memory where a heap dump could expose it.

    IntermediateQuick answer1 min read
  30. Why use ExecutorService instead of creating threads with new Thread?

    Thread creation is costly and unbounded threads can exhaust memory. An ExecutorService reuses a fixed set of worker threads, queues extra tasks, returns Futures, and offers an orderly shutdown.

    IntermediateQuick answer1 min read