Considering the code below:
- How is the
str1
object created without usingnew String()
? - Why do the
str1
andstr2
objects refer to same memory location?
String str1 = "hello";
String str2 = "hello";
Considering the code below:
str1
object created without using new String()
?str1
and str2
objects refer to same memory location? String str1 = "hello";
String str2 = "hello";
It is all described in the java language specification.
Each string literal is a reference (§4.3) to an instance (§4.3.1, §12.5) of class String (§4.3.3). String objects have a constant value. String literals-or, more generally, strings that are the values of constant expressions (§15.28)-are "interned" so as to share unique instances, using the method String.intern.
In java you can create String objects without calling the new operator.So, String str1 = "hello"
is equivalent to String str1 = new String("hello")
. It is done like this, to make the string declaration similar to the primitive data types.
regarding why are they referring to same memory location:
In java there is a concept of String literal pool.To cut down the number of String objects created in the JVM, the String class keeps a pool of strings. Each time your code create a string literal, the JVM checks the string literal pool first. If the string already exists in the pool, a reference to the pooled instance returns. If the string does not exist in the pool, a new String object instantiates, then is placed in the pool.
String str1 = "Hello";
String str2 = "Hello";
System.out.print(str1 == str2);
Prints True
.
If you do :
String str1 = "Hello";
String str2 = new String("Hello");
System.out.print(str1 == str2);
Prints False
.
because, String object is created out of the String literal pool.
"hello" is a string literal in Java. Java creates a pool of string literals because strings are immutable and reusable. By new String("hello")
you will be creating an extra string object even though the equivalent literal already exists in the pool.
As the string javadoc suggests
String str1 = "hello";
is equivalent to
char data[] = {'h', 'e', 'l', 'l', 'o'};
String str = new String(data);
And As Java Language Specification suggests Constant strings (in this case "hello"
) are String.interned meaning they share same memory and refer to same reference. All interend strings are stored in a String constant pool (see this post for details Identify library file/Source that contains native method implementation)
strings that are the values of constant expressions (§15.28)-are "interned" so as to share unique instances, using the method
However if you do create it with new String()
yourself, new memory will be allocated
String str = "hello";
String str1 = new String(str);
String str2 = new String(str);
assert: str1 != str2;
//Force strings into constant pool
String str3 = str1.intern();
String str4 = str2.intern();
assert: str == str3;
assert: str3 == str4;