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. 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
  6. 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
  7. Write Java code to sort employees by salary (highest first) and then by name.

    Build a Comparator with Comparator.comparingDouble(Employee::salary).reversed().thenComparing(Employee::name) and pass it to list.sort. Sorting costs O(n log n) time.

    IntermediateQuick answerCoding1 min read