String S1 = "ABC"; and string S2 = new string ("ABC");-Thoughts on java stack and heap

Source: Internet
Author: User

When I learned objective Java, I encountered the following problem: Avoid creating repeated objects. Think of a very basic problem: string. I also searched for the differences between the questions. At that time, I seemed to understand them. I 'd like to leave it unclear. So I searched the internet and found that this buddy wrote well. Therefore, it is easy to learn later.

The combination of http://developer.hi.baidu.com/#/detail/49198505is easier to read.

1. Both stack and heap are places where Java is used to store data in Ram. Unlike C ++, Java automatically manages stacks and stacks, and programmers cannot directly set stacks or stacks.

2. The advantage of stack is that the access speed is faster than the heap speed, second only to the registers directly located in the CPU. However, the disadvantage is that the data size and lifetime in the stack must be fixed, and there is a lack of flexibility. In addition, stack data can be shared. For details, refer to the 3rd point. The advantage of heap is that the memory size can be dynamically allocated, and the lifetime does not have to be told to the compiler in advance. The Java garbage collector will automatically collect the data that is no longer used. However, the slow access speed is due to the need to dynamically allocate memory during runtime.

3. There are two data types in Java.
One is the basic type (primitive types). There are eight types, namely int, short, long, byte, float, double, Boolean, char (note, there is no basic string type ). The definition of this type is defined in the form of int A = 3; long B = 255l;, which is called an automatic variable. It is worth noting that the automatic variable stores the literal value, not the instance of the class, that is, it is not the reference of the class, and there is no class here. For example, int A = 3; here, A is a reference pointing to the int type, pointing to the literal value of 3. Because of the size and lifetime of the nominal value data, we can see that (these nominal values are fixed in a program block, and the field value disappears after the program block exits). For the reason of speed, it exists in the stack.
In addition, the stack has a very important feature, that is, data in the stack can be shared. Suppose we define both

Int A = 3;
Int B = 3;

The compiler first processes int A = 3; first, it creates a reference with the variable A in the stack, and then finds whether there is an address with the nominal value 3, not found, open up an address that stores the nominal value of 3, and then point A to the address of 3. Then process int B = 3. After the referenced variable of B is created, B is directed to the address of 3 because there is already 3 in the stack. In this way, both A and B point to 3 at the same time.

Note that the reference of this literal value is different from that of a Class Object. Assume that the references of two class objects point to one object at the same time. If an object's reference variable modifies the internal state of the object, the variable referenced by the other object immediately reflects this change. On the contrary, modifying the value by referencing the literal value does not cause another reference value pointing to the literal value to change. In the preceding example, after defining the values of A and B, make a = 4; then, B is not equal to 4 or 3. In the compiler, when a = 4; is encountered, it will re-search whether there is a 4-character nominal value in the stack, if not, re-open the address to store the 4 value; if yes, direct a to this address. Therefore, changing the value of A does not affect the value of B.

The other is the packaging class data, such as integer, String, double, and so on. All the data of these classes exist in the heap. Java uses the new () statement to display and tell the compiler that the class is dynamically created as needed during runtime, so it is flexible, however, the disadvantage is that it takes more time.

4. string is a special packaging data. You can use the string STR = new string ("ABC"); or the string STR = "ABC"; (for comparison, before JDK 5.0, you have never seen an integer I = 3; expression, because the class and the literal value are not generic, except the string. In JDK 5.0, this expression is acceptable! Because the compiler converts integer I = new INTEGER (3) in the background ). The former is the process of creating a standardized class, that is, in Java, everything is an object, and the object is a class instance, all created in the form of new. Java
Some Classes in, such as the dateformat class, can return a newly created class through the getinstance () method of the class, which seems to violate this principle. Actually not. This class uses the singleton mode to return the instance of the class, but this instance is created in the class through new (), and getinstance () hides this detail from the outside. Why didn't I use new () to create an instance in string STR = "ABC"; is it against the above principles? Actually no.

5. About the internal work of string STR = "ABC. Java converts this statement into the following steps:
(1) first define a reference variable for the string class object named STR: String STR;
(2) check whether there is an address with the "ABC" storage value in the stack. If not, open an address with the "ABC" Storage name, create a new string class Object o, point the O string value to this address, and write down the referenced object o next to this address in the stack. If an address with a value of "ABC" already exists, search for the object O and return the o address.
(3) Point STR to the address of object o.
It is worth noting that the string values in the string class are stored directly. However, for example, string STR = "ABC"; in this case, the string value stores a reference pointing to data in the stack!

To better illustrate this problem, we can use the following code for verification.

String str1 = "ABC ";
String str2 = "ABC ";
System. Out. println (str1 = str2); // true

Note that str1.equals (str2); is not used here, because it will compare the values of the two strings to see if they are equal. =. According to JDK instructions, the true value is returned only when both references point to the same object. What we need to see here is whether both str1 and str2 point to the same object.
The result shows that JVM creates two references to str1 and str2, but only creates one object, and both references point to this object.

Let's go further and change the above Code:

String str1 = "ABC ";
String str2 = "ABC ";
Str1 = "BCD ";
System. Out. println (str1 + "," + str2); // BCD, ABC
System. Out. println (str1 = str2); // false

This means that the change in value assignment leads to the change in Class Object Reference. str1 points to another new object! Str2 still points to the original object. In the above example, when we change the str1 value to "BCD", the JVM opens up the address when it finds that the value is not stored in the stack, and creates a new object whose string value points to this address.
In fact, the string class is designed as an immutable class. If you want to change its value, yes, but during the runtime, the JVM quietly creates a new object based on the new value, and then returns the address of this object to the reference of the original class. Although the creation process is completely automatic, it takes more time. In environments with time-sensitive requirements, there may be adverse effects.

Then modify the original code:

String str1 = "ABC ";
String str2 = "ABC ";

Str1 = "BCD ";

String str3 = str1;
System. Out. println (str3); // BCD

String str4 = "BCD ";
System. Out. println (str1 = str4); // true

The reference of str3 directly points to the object pointed to by str1 (note that str3 does not create a new object ). After str1 has changed its value, create another string reference str4 and point it to the new object created by modifying the value of str1. It can be found that this time str4 has not created a new object, so as to share data in the stack again.

Let's look at the following code.

String str1 = new string ("ABC ");
String str2 = "ABC ";
System. Out. println (str1 = str2); // false

Two references are created. Two objects are created. The two references point to two different objects.

String str1 = "ABC ";
String str2 = new string ("ABC ");
System. Out. println (str1 = str2); // false

Two references are created. Two objects are created. The two references point to two different objects.

The above two sections of Code describe that as long as new () is used to create an object, it will be created in the heap, and its string is stored separately, even if it is the same as the data in the stack, it will not share data with the stack.

6. The value of the Data Type package class cannot be modified. Not only the values of the string class cannot be modified, but the internal values of all data type packaging classes cannot be changed.

7. Conclusion and suggestions:

(1) When we define a class using a format such as string STR = "ABC";, we always take it for granted that we have created the string class Object Str. Worry trap! The object may not be created! The only difference is that the reference to the string class is created. Whether the reference actually points to a new object must be considered based on the context, unless you explicitly create a new object through the new () method. Therefore, to be more accurate, we have created a reference variable STR pointing to an object of the string class, which points to a string class with a value of "ABC. It is helpful to be aware of this point to exclude bugs that are hard to be found in the program.

(2) using string STR = "ABC"; can improve the program running speed to a certain extent, because the JVM automatically determines whether it is necessary to create a new object based on the actual data in the stack. For the code of string STR = new string ("ABC");, a new object is created in the heap, regardless of whether the string value is equal, whether it is necessary to create a new object, this increases the burden on the program. This idea should be about the metadata-sharing model, but it is not clear whether the internal implementation of JDK applies this model here.

(3) Use the equals () method to compare the values in the packaging class. Use = to test whether the references of the two packaging classes point to the same object.

(4) because of the immutable property of the string class, when the string variable needs to change its value frequently, the stringbuffer class should be considered to improve program efficiency.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.