Junior — Middle
What are the differences between creating string objects using double quotes and the new String constructor?
sobes.tech AI
Answer from AI
When creating strings in Java using double quotes, for example String s = "hello";, the string literal is placed in the string pool. If such a string already exists in the pool, the variable simply references the existing object, which saves memory.
Using the constructor new String("hello") creates a new object on the heap, even if such a string already exists in the pool. This means that new String() always creates a new instance and does not reuse existing ones.
Example:
String a = "test";
String b = "test";
String c = new String("test");
System.out.println(a == b); // true, both refer to the same object in the pool
System.out.println(a == c); // false, c is a new object
Therefore, using double quotes is preferable for memory efficiency and performance.