Interview Question

What is the difference between String literals and new String()?

Literals are interned; new String creates a separate object with equal content.

💡 Concept ✅ Quick Revision ☕ Java

Answer

A string literal denotes an interned String instance; new String explicitly creates a new String object. • Equal literals in the same run-time string pool can share identity. • new String(\"x\") has equal content but normally distinct identity from the pooled literal. • Use equals for content comparison.

Example

Code
String literal = "Java";
String created = new String("Java");
System.out.println(literal == created);
System.out.println(literal.equals(created));
Output
false
true

Quick Revision

Literals are interned; new String creates a separate object with equal content.