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 →
- How does a HashSet avoid storing duplicates in Java?
A HashSet is backed by a HashMap and stores each element as a key. add() uses hashCode to find the bucket and equals to check for an existing equal element; if one exists the add returns false and nothing is stored.
BeginnerQuick answer1 min read - What causes ConcurrentModificationException and how do you avoid it?
It is thrown when a collection is structurally modified while you iterate over it, for example calling list.remove() inside a for-each loop. Remove through the Iterator, use removeIf, or iterate over a copy.
BeginnerQuick answer1 min read - What is the difference between Comparable and Comparator in Java?
Comparable defines one natural order inside the class itself through compareTo. Comparator is a separate object with a compare method, so you can define many different orderings without changing the class.
BeginnerQuick answer1 min read - What is the difference between HashMap, LinkedHashMap and TreeMap?
HashMap has no guaranteed order and gives O(1) operations. LinkedHashMap keeps insertion order, also in O(1). TreeMap keeps keys sorted and costs O(log n). Pick by the order you need.
BeginnerQuick answer1 min read - 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