How many objects are created for identical strings?
Two identical string literal assignments would create two separate string references, but they would both refer to the same string object. This is a special optimisation case that is supported by the fact that string objects are immutable in Java. Once a Java String object is created it cannot be changed, so it is safe for any number of identical string literal references to point to a single String object. The Java compiler marks string literals in a way that the Java Virtual Machine can identify and add to its String Literal Pool, a collection of references to Java string objects. If identical string literals are found at runtime the String Literal Pool provides a reference to the first instance of the string, and no duplicate String object is created. That means that two identical string literals refer to the same Java object. This optimisation does not apply to strings declared with the new String() constructor, as the examples below demonstrate. … full answer hidden, click here fo
Two identical string literal assignments would create two separate string references, but they would both refer to the same string object. This is a special optimisation case that is supported by the fact that string objects are immutable in Java. Once a Java String object is created it cannot be changed, so it is safe for any number of identical string literal references to point to a single String object. The Java compiler marks string literals in a way that the Java Virtual Machine can identify and add to its String Literal Pool, a collection of references to Java string objects. If identical string literals are found at runtime the String Literal Pool provides a reference to the first instance of the string, and no duplicate String object is created. That means that two identical string literals refer to the same Java object. This optimisation does not apply to strings declared with the new String() constructor, as the examples below demonstrate. … full answer hidden, click here fo