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 →
- What is the difference between ArrayList and LinkedList in Java?
ArrayList is backed by a resizable array, so reading by index is O(1) but inserting or removing in the middle shifts elements. LinkedList is a doubly linked list, so adding or removing at the ends is O(1) but reaching an index means walking the nodes. In practice ArrayList is the better default almost every time.
IntermediateIn-depth3 min read - 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 - 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 - 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