Junior — Middle
What happens in Java if you try to create a string that already exists in the string pool?
sobes.tech AI
Answer from AI
In Java, strings are immutable objects and are stored in the String Pool to save memory.
If you try to create a string that already exists in the String Pool:
- When using literals, for example
String s = "hello";, the JVM checks the String Pool and returns a reference to the existing object. - When creating a string with
new String("hello"), a new object is created on the heap, even if such a string exists in the pool.
To explicitly get a string from the pool for an object created with new, you can call the intern() method:
String s1 = "hello";
String s2 = new String("hello");
String s3 = s2.intern();
System.out.println(s1 == s3); // true
System.out.println(s1 == s2); // false
Thus, if the string already exists in the pool, intern() will return a reference to it, avoiding duplication.