A String literal and a String object both represent text data in Java, but they differ in how they are created, stored in memory, and managed by the JVM. String literals are stored in the String Pool for reuse, whereas String objects created with the new keyword are allocated in heap memory as separate objects.
Key Points: • String literals are stored in the String Pool, which helps save memory by reusing existing strings. • String objects created using new String() are always created in heap memory, even if an identical value already exists in the pool. • Multiple string literals with the same value share the same memory reference. • Using new String() creates a new object every time, increasing memory usage. • String literals are generally preferred when object uniqueness is not required.
Example: If two variables are assigned the literal "Java", both point to the same object in the String Pool. However, if a String is created using new String("Java"), a separate object is created in heap memory.
Code Example:
public class Demo {
public static void main(String[] args) {
String str1 = "Java";
String str2 = "Java";
String str3 = new String("Java");System.out.println(str1 == str2); // true System.out.println(str1 == str3); // false System.out.println(str1.equals(str3)); // true
}
}Difference Between String Literal and String Object:
String Literal: • Created using double quotes ("Java") • Stored in the String Pool • Reuses existing objects • More memory efficient
String Object: • Created using new String("Java") • Stored in Heap Memory • Creates a new object every time • Consumes more memory
Interview Tip: A concise interview answer is:
"A String literal is stored in the String Pool and can be shared by multiple references, improving memory efficiency. A String object created using new String() is stored separately in heap memory and creates a new object every time, even if the same value already exists in the String Pool."