Java Stack Understanding

Source: Internet
Author: User

Heap and Stack in Java

Java divides memory into two types: one is stack memory, and the other is heap memory.

1. Stacks and heaps (heap) are places where Java is used to store data in RAM (random access memory). Unlike C + +, Java automatically manages stacks and heaps, and programmers cannot directly set up stacks or heaps.

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. 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 that 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;

is defined by the form, called an automatic variable.
It is worth noting that the automatic variable is a literal value, not an instance of a class, that is not a reference to a class, there is no class here.
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 that has no literal value of 3, and does not find it, opening up a storage 3 of this
The address of the literal value, and then point A to the address of 3.
then the int b = 3 is processed, and after the reference variable of B is created, because there is already 3 in the stack, B points directly to the 3 address
In this case, A and B both point to 3.

/************************************************************************************************************** ********************/

It is particularly important to note that the reference to this literal is different from the reference to the class object.

Assuming 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 that change.

Conversely, modifying 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. So the change of a value does not

The value that rang to 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. All of these classes of data exist in the heap, and Java uses new ()
Statements to show to the compiler, which are dynamically created at run time as needed, are more flexible, but the disadvantage is that it takes more time.
In Java, there are six different places where data can be stored:
1. Register (Register). This is the fastest storage area because it is located in a different location from the other store-the inside of the processor. But the number of registers is extremely limited, so
Registers are allocated by the compiler on demand. You cannot directly control or feel any sign of register presence in the program.
2. Stacks (Stack). is located in Universal RAM, but it can be supported from the processor with its "stack pointer". If the stack pointer moves down, the new memory is allocated;
Move up, the memory is freed. This is a fast and efficient method of allocating storage, second only to registers. When you create a program, the Java compiler must know what is stored in the stack
There is the exact size and life cycle of the data, because it must generate the appropriate code to move the stack pointer up and down. This constraint limits the flexibility of the program, so while some ja
VA data is stored on the stack-especially object references, but Java objects do not store them.
3. Heap. A universal memory pool (also available in RAM) for storing so Java objects. The benefit of a heap that differs from the stack is that the compiler does not need to know what to do from the heap
And do not have to know how long the stored data will survive in the heap. Therefore, there is great flexibility in allocating storage in the heap. When you need to create an object
, you only need new to write a simple line of code, and when you execute this line of code, the storage allocation is automatically made in the heap. Of course, for this flexibility you have to pay the code accordingly. With a heap
Storage allocation takes more time than storage storage with the stack.
4. Static storage (storage). "Static" here means "in a fixed position". The data stored in the static store that persists while the program is running. You can use the keyword static
To identify a particular element of an object is static, but the Java object itself never resides in a static storage space.
5. Constant storage (constant storage). Constant values are usually stored directly inside the program code, and it is safe to do so because they are never changed. Sometimes, in embedded
System, the constants themselves are separated from the rest, so in this case, you can choose to place them in ROM
6. Non-RAM storage. If the data is completely outside of the program, it can be free from any control of the program and can exist when the program is not running.
As far as speed is concerned, there are the following relationships:
Registers < Stacks < Heaps < other

"Thinking in Java" from the above phrase
Question one:

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


Question two:
String str1 =new string ("abc");
String str2 =new string ("abc");
System.out.println (STR1==STR2); False
Question three:
String S1 = "Ja";
String s2 = "va";
String s3 = "Java";
String S4 = s1 + s2;
System.out.println (s3 = = S4);//false
System.out.println (S3.equals (S4));//true

Some of the basic types of variables and object reference variables defined in the function are allocated in the stack memory of the function.

When a variable is defined in a block of code, Java allocates a memory space for the variable in the stack, and when the scope of the variable is exceeded, Java automatically frees the memory space allocated for that variable, which can be used immediately by another.

Heap memory is used to hold objects and arrays created by new.

The memory allocated in the heap is managed by the automatic garbage collector of the Java Virtual machine.
After generating an array or an object in the heap, you can also define a special variable in the stack that is equal to the first address of the array or object in the heap memory, and this variable in the stack becomes the reference variable of the array or object.
A reference variable is a name that is an array or an object, and you can use reference variables from the stack to access the arrays or objects in the heap later in your program.
In particular, say:
Stacks and heaps are places that Java uses to store data in RAM. Unlike C + +, Java automatically manages stacks and heaps, and programmers cannot directly set up stacks or heaps.
The Java heap is a run-time data area in which objects 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. Heap is responsible for 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 garbage collector 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.
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.
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.

String str1 =new string ("abc");
String str2 =new string ("abc");
System.out.println (STR1==STR2); False
The new method is to generate different objects. Each time one is generated.
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. (not necessarily, because if not beforehand, then will create, this is to create the object, if the original, then point to the original object on it)! 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. Because of the immutable nature of the string class, you should consider using the StringBuffer class to improve program efficiency when a string variable needs to change its value frequently.

Java Stack Understanding

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.