all, i faced a problem when a write the code below
String hello = "Hello";
String str5 = "Hel" + "lo";
String str8 = "Hel";
String str9 = "lo";
String str10 = str8 + str9;
System.out.println("str10==hello?" + (str10 == hello));
System.out.println("str5==hello?" + (str5 == hello));
System.out.println("str10==str5?" + (str10 == str5));
then i run my code and the console print this
str10 == hello ? false
str5 == hello ? true
str10 == str5 ? false
this confused me a lot. why the second print TRUE but the first print FALSE??
in my comprehension of String literal pool,when a string defined and JVM will check if the pool contains that string,if not ,put the string into the pool.
in my code,variable hello exists in string pool,"Helo" and "lo" also in the pool,my question is
my jdk version :1.6.0_29
my IDE:Intellij Idea 11.2
anyone can point it out? thank you very much
String literal in Java is a set of characters that is created by enclosing them inside a pair of double quotes. In contrast, String Object is a Java is a set of characters that is created using the new() operator. Thus, this explains the main difference between string literal and string object.
In summary here, is the important difference in String pool in Java 6 and 7: String pool is relocated to Java heap space from PermGen space. The default size of String pool is increased to 600013 entries from 1009 in Java 6. The -XX:StringTableSize JVM option is provided to specify the size of the String pool.
String Pool in Java is a special storage space in Java Heap memory where string literals are stored. It is also known by the names - String Constant Pool or String Intern Pool. Whenever a string literal is created, the JVM first checks the String Constant Pool before creating a new String object corresponding to it.
When we create a String object using the new() operator, it always creates a new object in heap memory. On the other hand, if we create an object using String literal syntax e.g. “Baeldung”, it may return an existing object from the String pool, if it already exists.
It behaves as it should. It is adressed in two sections of the JLS.
JLS #3.10.5:
strings that are the values of constant expressions (§15.28) - are "interned" so as to share unique instances, using the method String.intern.
JLS #15.28 lists what is considered as a constant expression. In particular, string literals are constant expressions ("Hel" and "lo") but for a variable to be considered a constant, it needs to be final.
In your case, if you change your code slightly to make str8
and str9
constant, you will get true
three times:
final String str8 = "Hel";
final String str9 = "lo";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With