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