How does the JVM create objects when you create a String object using new operator?
How does the JVM create objects when you create a String object and call its intern method?
To answer the first question, whenever you create a String literal, the JVM internally checks whether there is any object already existing with the same value satisfying the equals() method of the string. If any such object already exists, then the reference to that existing object is returned. Also do note that, any change to this returned reference's value will not affect the string because String is immutable. So, a new string object will be created and the new value will be assigned to the newly created object and will be returned to the reference while the retrieved string will not be changed.
If you create 100 String literals with the value "Hello", all the references to those 100 literals will be the same. You can cross check this using the == operator.
Coming to the second question, whenever you create an object using the new keyword, the JVM will not check for any existence of any object instead it will create a new String object and return its reference. Even though there is a string existing with the same value, the JVM will return a new string because of the presence of the new keyword. Consider you create a string literal,
String str = "hello";
and a string object using new keyword
String str1 = new String("hello");
The two strings' value may be equal but both the references will be pointing to two different objects. You can cross check this using the == operator. If you create another string literal now with the value "hello", then the reference of the first variable, str will be returned to the new literal.
The third question will reveal one of the optimization mechanisms used by the JVM. Consider you create a String object using the new keyword.
String str = new String("Hello");
If you call the intern method of this String object,
str = str.intern();
the JVM will check whether the String pool maintained by the JVM contains any String objects with the same value as the str object with the equals method returning true. If the JVM finds such an object, then the JVM will return a reference to that object present in the String pool. If no object equal to the current object is present in the String pool, then the JVM adds this string into the String pool and returns its reference to the calling object. The JVM adds the object to the String pool so that the next time when any string object calls the intern method, space optimization can be done if both of these strings are equal in value. You can check the working of intern method using the equals and == operators.