Junior — Middle
How does creating a string with the new operator differ from assigning a literal in quotes?
sobes.tech AI
Answer from AI
In Java, strings are created mainly in two ways: through literals and through the new operator.
-
When creating a string using a literal, for example,
String s = "hello";, the string is placed in the string pool. If such a string already exists in the pool, the variable will reference the existing object, which saves memory. -
When using the
newoperator, for example,String s = new String("hello");, a new object is created on the heap, even if such a string already exists in the pool. This results in creating an additional object and increasing memory usage.
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
Thus, using literals is more memory-efficient and allows you to take advantage of the string pool.