Java stack-related knowledge

Source: Internet
Author: User
Tags format definition

Java Stack and heap


The content of this blog is collected from the Internet, and the author has changed and organized it into


1. Stacks and heaps (heap) are places that Java uses to store data in RAM. Unlike C + +, Java Automatic management stacks and heap programmers cannot set up stacks or heaps directly.

2.the advantage of the stack is that the access speed is faster than the heap, second only to the registers directly in the CPU。 However, the disadvantage is that the size and lifetime of the data in the stack must be deterministic and inflexible. In addition, the stack data can be shared, see 3rd.the advantage of the heap is that the memory size can be allocated dynamically, and the lifetime does not have to tell the compiler beforehand, the Java garbage collector automatically collects the data that is no longer in use. However, the disadvantage is that the access speed is slower due to the dynamic allocation of memory at run time.

3. There are two kinds of data types in Java.

One is the basic type (primitive types), a total of 8 kinds, namely int, short, long, byte, float, double, Boolean, char (note, and no basic type of string). The definition of this type is through such as int a = 3; Long B = 255L; Of the form to define,called an automatic variable. It is important to note that the automatic variable is literal, not an instance of the class, that is, not a reference to the class, where there is no class.。 such as int a = 3; Here A is a reference to the int type, pointing to the literal value of 3. The data of these literals, due to the size of the known, the lifetime of the known (these values are fixed in a program block, the program block exits, the field value disappears), for the sake of speed, it exists in the stack.

In addition, the stack has a very important particularity, is that there is data in the stack can be shared. Let's say we define both:
int a = 3;
int b = 3;
The compiler processes int a = 3 First, it creates a reference to a variable in the stack, and then looks for an address with a literal value of 3, finds an address that holds the literal value of 3, and then points A to the address of 3. then the int b = 3 is processed, and after the reference variable of B is created, B is pointed directly to the address of 3 because there are already 3 literals in the stack. In this case, A and B both point to 3.

the special attention isThisLiteral valueis different from the reference to the class object. Assume that a reference to two class objects points to an object at the same time,If an object reference variable modifies the internal state of the object, then another object reference variable will immediately reflect the change。 Insteadmodifying its value by a reference to a literal value does not result in another case where a reference to that literal is changed。 As in the example above, we define the value of a and B and then make a=4; then B will not be equal to 4 or equal to 3. Inside the compiler, when it encounters A=4, it will re-search the stack for a literal value of 4, and if not, re-open the value of the address 4, and if so, point a directly at the address. Therefore the change of a value does not affect the value of B.

The other is the wrapper class data, such as Integer, String, double, and so on, the corresponding basic data types are wrapped up class.These classes of data all exist in the heap,Java uses the new () statement to tell the compiler that it is dynamically created as needed 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"); In the form of string str = "abc" (In contrast, you have never seen an expression of integer i = 3 before JDK 5.0, because the class and literal literals are not generic except for string.) In JDK 5.0, this expression is possible! Because the compiler is converting the integer i = new Integer (3) in the background. The former is the process of creating a canonical class, that is, in Java, everything is an object, and the object is an instance of the 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 class's getinstance () method, which seems to violate this principle. actually otherwise The class uses a singleton pattern to return an instance of the class, except that the instance is created inside the class through new (), and getinstance () hides this detail from the outside. So why is the case in string str = "abc", not created by new (), a violation of the above principle? Not really.

5.about the internal work of string str = "ABC"。 Inside Java, this statement is translated into the following steps:

(1) First define an object reference variable named str to the String class: String str;

(2) in the stack to find whether there is a value of "ABC" address, if not, then open a store with a literal "ABC" address, then create a new String Class object O, and the string value of O point to the address, and in the stack next to this address note the referenced object o. If you already have an address with a value of "ABC", look for the object o and return the address of O.

(3) Point Str to the address of the object o.

It is important to note that the string values in the generic string class are directly stored values. But like string str = "abc"; In this case, the string value is a reference to the data in the existing stack!

To better illustrate this problem, we can verify it by following several 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, as this will compare the values of two strings for equality. = = number, as described in the JDK, returns true only if two references point to the same object. And what we're looking at here is whether str1 and str2 all point to the same object.
The result shows that the JVM created two references str1 and str2, but only one object was created, and two references 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, ABC
System.out.println (STR1==STR2); False
This means that the change in the assignment has led to 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 for that value in the stack, opens up this address and creates a new object whose string value points to the address.

In fact, the string class is designed to be immutable (immutable) classes. If you want to change its value, yes, 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 entirely automatic, but it takes up more time. In the environment that is more sensitive to time requirements, it will have some 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
STR3 a reference to this object points directly to the object that str1 points to (note that STR3 does not create a new object). When str1 changes its value, it creates a reference str4 of string and points to the new object created by str1 modifying the value. It can be found that this time STR4 also did not create a new object, thereby re-sharing the data in the stack.

Let's look at the following code again.
String str1 = new String ("abc");
String str2 = "abc";
System.out.println (STR1==STR2); False creates two references. Two objects were created. Two references point to a different two objects, respectively.

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 a different two objects, respectively.

The above two code shows that as long as new () is used to create the object, it is created in the heap, and its string is stored separately, even if the data in the stack is the same, it 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 cannot be modified, but 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 want to think of course that we created the object str of the String class. Worry about traps! The object may not have been created! The only certainty is that a reference to the string class was created . As to whether the reference is pointing to a new object, it must be considered in terms of context, unless you create a new object with a prominent way through the new () method. Therefore, it is more accurate to say that we have created a reference variable to the object of the String class str, which refers to a variable that points to a string class with the value "ABC". Being aware of this is helpful in troubleshooting bugs that are difficult to find in a program.

(2) The use of string str = "abc", in a way that can improve the speed of the program to a certain extent, because the JVM will automatically based on the actual data in the stack to determine whether it is necessary to create a new object. In the case of string str = new String ("abc"), the code creates a new object in the heap, regardless of whether the string value is equal or not, and it is necessary to create a new object, thereby aggravating the burden of the program. This idea should be the idea of the meta-mode, but it is not known whether the internal JDK implements this pattern.

(3) Use the Equals () method when comparing the values in the wrapper class, and use = = when testing whether the references to the two wrapper classes point to the same object.

That is, if you compare the contents of two objects with equals, compare whether two references are references to the same object using = =
(4) Because of the immutable nature of the string class, you should consider using the StringBuffer class when the string variable needs to change its value frequently to improve program efficiency.

Since here is a string str = "abc"; with string str = new String ("abc"); then expand it, String str = new String ("abc") creates several objects?

2 objects were created, respectively STR and "ABC"

Let's start with this question and review some of the Java knowledge associated with creating a string object.

We can think of this line of code as String str, =, "abc" and new String () four. String str simply defines a variable of type string named STR, so it does not create an object; = is initialized to the variable str, assigns a reference to an object (or a handle) to it, and apparently does not create an object; now only the new string ("abc") is left. The So why can new string ("abc") be considered "ABC" and new String ()?

Let's take a look at the constructor of the string we called:

public string (string original) {//other code ...} As we all know, there are two ways to create an instance of a class (object):

First, use new to create the object.

Second, call the class Newinstance method, using the reflection mechanism to create the object.

We created an object using the above constructor method that called the string class with new, and assigned its reference to the STR variable. At the same time, we notice that the called constructor method accepts parameters that are also a string object, which is "ABC". So we're going to introduce another discussion of how to create a string object-the quotation marks contain the text .

This method is unique to string , and it differs greatly from the way new is.

String str= "ABC"; An object is created here, but this object is not str,str just got a reference to "ABC"

There is no doubt that this line of code creates a string object.

String a= "ABC";   String b= "ABC"; What about here?

The answer is still one.

String a= "AB" + "CD"; And look here?

the answer is three.

In this case, we need to introduce a review of the knowledge associated with string pooling .

There is a string pool in the Java Virtual Machine (JVM) that holds many string objects and can be shared, so it improves efficiency. since the string class is final, its value cannot be changed once it is created, so we do not have to worry about the confusion of the program with the string object being shared . Strings are maintained by the string class, and we can call The Intern () method to access the string pool.

We look back at string a= "abc"; When this line of code is executed, the Java Virtual machine first looks in the string pool for the existence of an object with the value "ABC", which is judged by the string class equals(object Obj) method returns a value. If there is, no new object is created, the reference to the existing object is returned directly, if not, the object is created first, then added to the string pool, and its reference is returned. Therefore, it is not difficult to understand why the first two examples in the previous three examples are the answer.

A new object that is created with a "+" connection between a string object that uses quotation marks to contain text is added to the string pool. For all "+" join expressions that contain new objects (including null), the new object is not added to the string pool, and we will not repeat them. so we encourage you to create string objects in quotes that contain text, which is actually what we often use in programming.

Stack: A reference to a primary save base type (or built-in type) (char, Byte, short, int, long, float, double, Boolean), and object, data can be shared, second only to register (register), faster than heap.

Heap: Used to store objects


This article is from the "Punk" blog, please be sure to keep this source http://yimaoqian.blog.51cto.com/1328422/1608080

Java stack-related knowledge

Related Article

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.