Click to enter _ more _java thousand ask
1. How string is stored in memory
Learn what a string looks here: what is a string
String is a special wrapper class data.
You can create them in two ways:
StringnewString"abc" );String"abc" ;
Learn how Java manages memory look here: How the JVM manages memory
Learn the differences between Java heap and stack see here: What is the difference between Java heap and stack
The first is to create a new object with new (), which will be stored in the heap, and will be created for each call.
The second is to create an object reference variable str to the String class in the stack, and then find out if there is no "ABC" in the string pool in the heap, and if not, put "ABC" into the string pool and make str point to "ABC" if there is already "ABC" The STR directly points to "ABC".
2. How to use the Equals method of string
Use the Equals () method when comparing values within a class, and when testing two wrapper classes for reference to the same object, use = = (which can be understood as comparing logical addresses, which is actually compared to the object number), with an example to illustrate the above theory.
String"abc" ;String"abc"//true
You can see that str1 and str2 are pointing to the same object.
StringnewString"abc" );StringnewString"abc"// false
-
For the second way (string str1 = "abc") to create multiple "abc" strings, there is actually only one object in memory. This saves memory space, and it can increase the speed of the program to some extent, because the JVM automatically determines whether it is necessary to create new objects based on the actual facts of the data in the string pool.
-
For the first way, string str = new String ("ABC") creates new objects in the heap, regardless of whether their string values are equal, and it is necessary to create new objects, thereby aggravating the burden on the program.
Another point to note: When defining a class using a format such as String str = "ABC", we always want to assume, of course, that the object of the string class was created by Str. There is a fear of traps: objects may not be created! Instead, it might just point to an object that was previously created. Only through the new () method can you guarantee that a new object is created each time.
Because of the immutable (immutable) nature of the string class, you should consider using the Stringbuffer/stringbuilder class to improve program efficiency when a string variable needs to change its value frequently.
Stringbuffer/stringbuilder difference look here: Stringbuffer/stringbuilder what is the difference
Java thousands ask _06 data structure (022) _string in memory how to store