Saturday, July 1, 2017

String Literals as Constants or Singletons

If you use the same string (e.g. "Hello World") in other String variable declarations, the Java virtual machine may only create a single String instance in memory. The string literal thus becomes a de facto constant or singleton. The various different variables initialized to the same constant string will point to the same String instance in memory. Here is a Java String constant / singleton example:
String myString1 = "Hello World";
String myString2 = "Hello World";
In this case the Java virtual machine will make both myString1 and myString2 point to the same String object.
More precisely, objects representing Java String literals are obtained from a constant String pool which the Java virtual machine keeps internally. That means, that even classes from different projects compiled separately, but which are used in the same application may share constant String objects. The sharing happens at runtime. It is not a compile time feature.
If you want to be sure that two String variables point to separate String objects, use the new operator like this:
String myString1 = new String("Hello World");
String myString2 = new String("Hello World");
Even though the value (text) of the two Java Strings created is the same, the Java virtual machine will create two different objects in memory to represent them.

@reference_1_jenkov.com

No comments:

Post a Comment