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 == and equals() in Java, and what is the String pool?
== checks whether two references point to the same object, while equals() checks whether two objects have the same content (if the class overrides it, as String does). String literals are stored once in the String pool, which is why two identical literals can be == but new String("x") cannot.
BeginnerIn-depth3 min read - How many objects does new String("India") create in Java?
Up to two. The literal "India" goes into the string pool if it is not already there, and new String(...) always creates a separate object on the heap. So two objects the first time, and one if the pool already had the literal.
BeginnerQuick answer1 min read - What does the intern() method of String do?
intern() returns the pooled copy of a string. If the pool already holds an equal string it returns that one, otherwise it adds this string to the pool and returns it, so interned strings with equal text compare equal with ==.
IntermediateQuick answer1 min read