String str = "abc" and String str = new String ("abc"), stringstrabcnew
1. the java Runtime Environment has a String pool maintained by the String class. When the statement String str = "abc" is executed:
1. first, check whether the string "abc" exists in the string pool. If yes, assign "abc" to str. If not, create a new string "abc" in the string pool ", and then assign it to str.
2. Execute the statement String str = new String ("abc. No matter whether the string "abc" exists in the string pool, directly create a new string "abc" (note that the new string "abc" is not in the string pool) and then assign it to str
It can be seen that 1. The efficiency is higher than 2.
3. String str1 = "java"; // point to the String pool
String str2 = "blog"; // point to the String pool
String s = str1 + str2; + operator creates two String objects in the heap. The values of these two objects are "java", "blog ", that is to say, copy the two values from the String constant pool, and then create two objects in the heap. Then create the object s, and then assign the heap address of "javablog" to s. This sentence creates three String objects.
System. out. println (s = "javablog"); // The result is false;
The JVM does put the object in the constant pool, such as String str = "javablog"; but it does the name at compilation. String s = str1 + str2; it can be known at runtime, that is, str1 + str2 is created in the heap, so the result is false.
String s = "java" + "blog"; // directly put the javablog object into the String pool. System. out. println (s = "javablog"); // The result is true;
String s = str1 + "blog"; // allocated in the heap instead of in the String pool. System. out. println (s = "javablog"); // The result is false;
In short, there are two ways to create a string: Two memory areas (pool, heap)
1. "" The created string is in the string pool.
2. when creating a new string, check whether the same string exists in the pool. If yes, copy the string to the heap and return the address in the heap. If no string exists in the pool, create a score in the heap, then return the address in the heap,
3. when assigning values to a string, if the right operand contains one or more string references, A String object is created in the heap, and a reference is returned, for example: string s = str1 + "blog ";