Two different instantiations of string types

Source: Internet
Author: User
Tags define definition expression format definition integer variable wrapper access
Original title: About Java stack and heap of thinking   1. Stacks and heaps (heap) are places where Java is used to store data in RAM.   Unlike C + +, Java automatically manages stacks and heaps, and programmers cannot directly set stacks or heaps. 2. The advantage of the stack is that access is faster than the heap, second only to the registers directly located in the CPU. The disadvantage is that the data size and lifetime in the stack must be fixed and inflexible. In addition, the stack data can be shared, as detailed in the 3rd. The advantage of the heap is that the memory size can be dynamically allocated, and that the Java garbage collector automatically collects the data that is no longer in use without having to tell the compiler beforehand.  The disadvantage is that the access rate is slow due to the dynamic allocation of memory at run time.  3. There are two types of data in Java. One is the basic type (primitive types), there are 8 kinds, that is, int, short, long, byte, float, double, Boolean, char (note that there is no basic type of string). This type of definition is passed through such as int a = 3; The form of long B = 255L is defined, called an automatic variable. It is worth noting that the automatic variable is a literal value, not an instance of the class, that is, not a reference to a class, where there is no class. such as int a = 3; Here's A is a reference to the int type, pointing to the literal value of 3.  These literal data, due to the size of known, lifetime known (these literals are fixed in a program block, the program block exit, the field value disappears), for the pursuit of speed reasons, exist in the stack. In addition, the stack has a very important particularity, is the existence of the stack of data can be shared. Suppose we define at the same time: int a = 3; int b = 3; the compiler handles int a = 3 First, it first creates a reference to a in the stack, and then looks for an address with a literal value of 3, then opens an address that holds the face value of 3, and then points A to the address of 3. Then deal with int b = 3, after creating the reference variable for B, the B directly points to the address of 3 because it already has 3 of the literal value on the stack.  In this way, there is a case where A and B both point to 3. It is particularly noteworthy that the reference to this literal is different from the reference to the class object. Assuming that references to two classes of objects also point to an object, if an object reference variable modifies the internal state of the object, then another object reference variable also instantly reflects the change. Conversely, modifying the value of a literal by reference does not result in another change in the value of the reference to that literal. As in the example above, we define the value of a and B and then make a=4; then, b is not equal to 4, or equal to 3. Inside the compiler, when you encounter a=4, it will search the stack for 4 literal values, and if not, reopen the address for a value of 4, and if so, point a directly to the address.  Therefore the change of a value does not affect the value of B. The other is wrapping class data, such as Integer, String, and double, which wraps the corresponding basic data types. All of these class data exist in the heap, and Java uses the new () statement to tell the compiler that it is dynamically created at run time, so it is more flexible, but the disadvantage is that it takes more time. 4. String is a special wrapper class data. That is, you can use string str = new String ("abc"); form, or it can be created in the form of String str = "abc" (In contrast, you have never seen an expression of integer i = 3 before JDK 5.0, because class and literal values are not can be generic except for string. In JDK 5.0, this expression is OK! Because the compiler is in the background for the integer i = new Integer (3) conversion). The former is the process of creating a canonical class, in Java, where everything is an object, and an object is an instance of a class, all created in the form of new (). Some classes in Java, such as the DateFormat class, can return a newly created class through the getinstance () method of the class, which seems to violate this principle. Fact The class uses a singleton pattern to return an instance of a class, except that the instance is created inside the class through new (), and getinstance () hides this detail externally. So why is it a violation of the above principles to create an instance in string str = "abc", and not through new ()?  No, actually. 5. Internal work on string str = "abc". Inside Java, this statement is translated into the following steps: (1) Define an object reference variable named str for the String class: String str; (2) Find an address in the stack that has a value of "ABC", or, if not, open an address with a literal "abc". Next, create a new String Class object O and Point O's string value to the address, and note the object o to the reference in the stack next to this address.  If you already have an address with the value "ABC", look for the object o and return the address of O.  (3) Point Str to the address of object o. It is noteworthy that the string values in the generic string class are stored directly. But like string str = "abc"; in this case, its string value holds a pointer to the data in the existing stack.The Reference! To better illustrate this issue, we can verify this by using several of the following code. String str1 = "abc"; String str2 = "abc"; System.out.println (STR1==STR2); True note that we do not use Str1.equals (STR2) in this way, because this compares the values of two strings to be equal. The = = number, as described in the JDK, returns the true value only if two references are pointing to the same object. And what we're looking at here is whether str1 and str2 all point to the same object.  As a result, the JVM created two references str1 and str2, but only one object was created, and two references all pointed to the object. Let's go further and change the above code to: String str1 = "abc"; String str2 = "abc"; str1 = "BCD"; System.out.println (str1 + "," + str2); BCD, AbcSystem.out.println (STR1==STR2); False This means that the change in assignment results in a change in the class object reference, and str1 points to another new object! And str2 still points to the original object.  In the example above, when we change the value of str1 to "BCD", the JVM discovers that there is no address in the stack that holds the value, opens up the address, and creates a new object whose string value points to the address. In fact, the string class is designed to be an immutable (immutable) class. If you want to change its value, you can, but the JVM silently creates a new object at run time based on the new value, and then returns the address of the object to the reference of the original class. This creation process is completely automated, but it takes up more time after all.  In the environment that is sensitive to the time requirement, it will have a certain adverse effect. Then modify the original code: String str1 = "abc"; String str2 = "abc"; str1 = "BCD"; String STR3 = str1; System.out.println (STR3); bcdstring STR4 = "BCD"; System.out.println (str1 = = STR4); True STR3 a reference to this object directly points to the object that str1 points to (note that STR3 does not create a new object). When STR1 has finished changing its value, it creates a reference str4 for string and points to a new object created by str1 modifying the value. Can be found, this time STR4 alsoNo new objects were created to enable the sharing of data in the stack again. Let's look at the following code again. String str1 = new String ("abc"); String str2 = "abc"; System.out.println (STR1==STR2); False two references were created. Two objects were created. Two references point to different two objects. String str1 = "abc"; String str2 = new String ("abc"); System.out.println (STR1==STR2); False two references were created. Two objects were created.  Two references point to different two objects.  The above two pieces of code show that as long as the new object is created with new (), it is built in the heap and its string is stored separately, even if it is the same as the data in the stack, and is not shared with the data in the stack. 6. The value of the data type wrapper class cannot be modified. Not only the value of the string class is not modifiable, all data type wrapper classes cannot change their internal values. 7. Conclusions AND Recommendations: (1) When we use a format definition class such as String str = "ABC", we always assume that we have created the object str of the String class. Worry about the traps! The object may not have been created! The only certainty is that a reference to the string class was created. Whether or not this reference is pointing to a new object must be considered in context, unless you are creating a new object by means of the new () method. So it's more accurate to say that we created a reference variable str that points to the object of the string class, which refers to a string class with a value of "ABC".  Waking up to this point is helpful in troubleshooting bugs that are hard to find in the program. (2) The use of string str = "ABC" can improve the speed of the program to some extent, because the JVM automatically determines whether it is necessary to create a new object based on the actual situation of the data in the stack. For code with string str = new String ("abc"), the new object is created in the heap, regardless of whether its string value is equal or not, and it is necessary to create a new object, which increases the burden on the program.  This thought should be the idea of the meta pattern, but it is not known whether the JDK's internal implementation of this pattern is applied here.  (3) When comparing the values within the wrapper class, use the Equals () method, or = = when the reference to the two wrapper class is pointing to the same object. (4) Because of the immutable nature of the string class, when the string variable needs to change frequentlyWhen changing the value, you should consider using the StringBuffer class 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.