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. 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
  2. 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
  3. 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
  4. 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
  5. 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
  6. 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
  7. Write Java code to find the second highest distinct number in a list.

    Sort the distinct values in descending order, skip the first, and take the next, returning an Optional because there may be no second value. The stream version is O(n log n); a single loop tracking two maximums is O(n).

    IntermediateQuick answerCoding1 min read
  8. Write Java code to group a list of names by their first letter using streams.

    Use Collectors.groupingBy with a classifier that returns the first character, and pass TreeMap::new if you want the keys sorted. It makes one pass, so O(n) time and O(n) space.

    IntermediateQuick answerCoding1 min read