Stacks in Java

Source: Internet
Author: User

1. Stack Overview

In layman's terms, stacks and heaps are places that Java uses to store data in RAM. The heap is primarily used to store objects and arrays created by new, and the stack is primarily a reference to variables and objects that store basic types, unlike C + +, where Java automatically manages stacks and heaps, and programmers cannot directly manipulate stacks or heaps.

The Java heap is a run-time data area in which the objects of the class allocate space. These objects are established through directives such as new, NewArray, Anewarray, and Multianewarray, and they do not require program code to be explicitly released. The heap is responsible for GC (garbage collection), the advantage of the heap is the ability to dynamically allocate memory size, the lifetime does not have to tell the compiler beforehand, because it is at runtime to allocate memory dynamically, Java GC mechanism will automatically take away these no longer use data. However, the disadvantage is that the access speed is slower due to the dynamic allocation of memory at run time.

The advantage of the stack is that the access speed is faster than the heap, after the register, the stack data can be shared. However, the disadvantage is that the size and lifetime of the data in the stack must be deterministic and inflexible. The stack mainly contains some basic types of variables (int, short, long, byte, float, double, Boolean, char) and object handle. (Note: This is not included string,string will be explained in the rear.)

Suppose we define a list object:

List List = new ArrayList ();

The process of executing the above statement in memory is to first produce a ArrayList object in the heap and then define a special variable list in the stack so that the value of this variable in the stack equals the first address of the ArrayList object in the heap memory. This variable in the stack becomes the reference variable of the ArrayList object. A reference variable is the equivalent of the name of the object, and you can use the reference variable in the stack to access the objects in the heap later in the program.

2 , the release of data in the stack

A reference variable is a normal variable that is allocated in the stack when defined, and the reference variable is freed after the program runs outside its scope. While the array and the object itself are allocated in the heap, the memory occupied by the array and the object itself is not freed when the program runs beyond the block of code that uses new to produce the array or object's statement, and the array and object become garbage when no reference variable points to it, not in use, but still occupy memory space. The GC is collected (released) at a later indeterminate time. This is why the Java comparison accounts for memory.

In fact, the variables in the stack point to the variables in the heap memory, which is the pointer in Java!

3, stack of data sharing

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 finds out if there is a value of 3 in the stack, and if it does not, it stores the 3 in and then points a to 3. then the int b = 3 is processed, and after the reference variable of B is created, because there are already 3 values in the stack, B points directly to 3. In this case, A and B both point to 3.

At this point, if you make a=4 again, then the compiler will re-search the stack for 4 values, if not, then store 4 in, and a point to 4; Therefore the change of a value does not affect the value of B.

It is important to note that this sharing of data with two object references also points to an object where this share is different, because the modification of a does not affect B, which is done by the compiler, which facilitates space saving. An object reference variable modifies the internal state of the object, affecting another object reference variable.

4. How to handle the string class

String is a special wrapper class data. Can be used:

String str = new String ("abc"); String str = "ABC";

Two forms, the first is to create new objects with new (), which is stored in the heap. A new object is created each time the call is made. The second is to create an object reference to the string class in the stack str, and then find whether there is no "ABC" in the stack, if not, put "ABC" into the stack, and make str point to "ABC", if there is already "ABC" directly to the "ABC" Str.

Use the Equals () method when comparing values within a class, and when testing two wrapper classes for reference to the same object, use = =, the following example illustrates the above theory.

String str1 = "abc"; String str2 = "abc"; System.out.println (STR1==STR2); True

You can see that str1 and str2 are pointing to the same object.

The new method is to generate different objects. Each time one is generated. As long as new () is used to create the object, it is created in the heap, and its string is stored separately, even if it is the same as the data in the stack, it is not shared with the data in the stack. But like string str = "abc"; In this case, the string value is a reference to the data in the existing stack!

So the second way to create multiple "abc" strings, in memory in fact there is only one object. This writing is advantageous and saves memory space. At the same time it can improve the speed of the program to some extent, because the JVM will automatically determine whether it is necessary to create new objects based on the actual data in the stack. 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.

On the other hand, it is important to note that when you define a class using a format such as String str = "ABC", you always want to assume, of course, that the object that created the string class is Str. Worry about traps! The object may not have been 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.

Add one point:

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.

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. Therefore, it is recommended to use StringBuffer when manipulating strings.

5, packing a little special place

Here is not the problem of stack, just a little bit of knowledge by the way to record.

Let's look at the following example:

Integer i1 = new Integer (3), Integer i2 = new Integer (3); System.out.println (I1 = = i2);//falseinteger i3 = new Integer (137); Integer i4 = new Integer (137); System.out.println (i3 = = i4);//falseinteger i5 = integer.valueof ("3"); Integer I6 = integer.valueof ("3"); SYSTEM.OUT.PRINTLN (i5 = = I6);//trueinteger i7 = integer.valueof ("137"); Integer i8 = integer.valueof ("137"); System.out.println (i7 = = i8);//falseinteger I9 = 3;integer i10 = 3; System.out.println (I9 = = i10);//trueinteger i11 = 137;integer i12 = 137; System.out.println (i11 = = i12);//false

For the basic data type, if within a byte, (that is, 128 ~ 127), once wrapped into an integer object, it will be placed in a buffer pool, when the next time you need to wrap the integer into an integer object, it will first look for the buffer pool there is no such object, Some change to take it directly. Small integers are all boxed up with the same object. This conclusion applies only to the automatic boxing operation, which is not appropriate if it is explicitly boxed (that is, the new method is used). Due to the high frequency of smaller integers, this operation saves memory space, which is called: the-->flyweight mode.

Supplement 1:

In a nutshell, a complete Java program will run with the following memory areas:

Register: JVM internal virtual register, access speed is very fast, the program is not controllable.

Stack: holds the value of the local variable, including: 1. The value used to hold the base data type; 2. Save an instance of the class, which is a reference (pointer) to the heap object . It can also be used to save the frame when the method is loaded.

heap: used to store dynamically generated data, such as new objects . Note the objects that are created contain only the member variables that belong to them, and do not include member methods. Because objects of the same class have their own member variables stored in their own heap, they share the methods of the class, and not every object is created to copy the member method one at a time.

constant Pool: The JVM maintains a constant pool for each loaded type, and the constant pool is an ordered set of constants used by this type. Includes direct constants (basic types, String) and symbolic references to other types, methods, and fields. The data in the pool is accessed through the same index as the array. Because a constant pool contains symbolic references to other types, methods, and fields for one type, Chang plays a central role in the dynamic linking of Java. A constant pool exists in the heap .

Code snippet: used to hold the source code read from the hard disk.

Data segment: a static member used to hold a static definition.

Note: This article part of the content from the Internet, the specific source is unclear. If the infringement of your relevant interests, please leave a message to inform, I will delete the relevant content as soon as possible.

Stacks in Java

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.