The difference between heap memory and stack memory in Java

Source: Internet
Author: User

Java divides memory into two types, called stack memory, which is called heap memory.

some 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 Java Virtual Machine automatic garbage collector. After creating an array or an object in the heap, you can also define a special variable in the stack that is equal to the array or the first address of the object in the heap memory, and this particular variable in the stack becomes the reference variable of the array or object. You can then use the reference variable in the stack memory in your program to access the array or object in the heap, which is the equivalent of an alias, or codename, of an array or object.

A reference variable is a normal variable that is defined when memory is allocated in the stack, and the reference variable is released in the program run to the extraterritorial scope. The array and object itself is allocated in the heap, and even if the program runs beyond the block of code that uses the new generation of arrays and objects, the heap memory that the array and the object itself occupies will not be freed, and arrays and objects become garbage, no longer used, but still occupy memory when no reference variable points to it. is released by the garbage collector at a later indeterminate time. This is also the main reason for the memory of Java comparison, in fact, the variables in the stack point to the heap memory variables, this is the pointer in Java!

Example 1 is as follows:

New Person ();

This is actually comprised of two steps, declarative and instantiated

Person per = null; Declares an object called the person class per

per = new person (); Instantiate this per object

A declaration refers to the process of creating an object of a class;

instantiation refers to using the keyword new to open up memory space.

Their partitioning in memory is this:

What is stack memory (heap) and stack memory (heap)?

Stack Memory:

Some of the basic types of variables and object reference variables defined in the function are allocated in the stack memory of the function. Stack memory primarily holds data of the basic type type (int, short, long, byte, float, double, Boolean, char) and object handle. Note: There is no string base type, the size of the data in the stack memory and the life cycle is to be determined, the advantage is that the storage speed is fast, the stack data can be shared, the disadvantage is that data is fixed, not flexible.

Sharing of Stacks:
  1  String str1 = "myString"   2   3  String str2 = "myString" ;   4   5  System.out.println (str1 ==str2);   6   7  //   Note: This is str1 ==str2 instead of Str1.equals (STR2).   8   9     because, according to the JDK description, the = = number returns the True value only if two references point to the same object    11  //  

The result is true, which shows that str1 and str2 are actually pointing to the same value.

The principle of the above code is to first create a reference in the stack with a variable of str1, and then find out if there is a mystring value in the stack, if not found, the mystring will be stored in, and then str1 point to MyString. The string str2 = "MyString" is then processed, and after the reference variable of STR2 is created, the STR2 is pointed directly to myString because there is already myString this value in the stack. In this way, str1 and str2 point to mystring.

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 STR1 and str2 and then make str1=yourstring, so str2 will not be equal to yourstring or mystring. Inside the compiler, when Str1=yourstring is encountered, it will re-search the stack for the literal value of yourstring, and if not, re-open the value of the address store yourstring, and if so, point str1 directly to the address. Therefore the change of the STR1 value does not affect the value of the str2.

Heap Memory:

Heap memory is used to hold all new created objects and arrays of data

1String str1 =NewString ("MyString");2  3String str2 = "MyString";4  5System.out.println (str1 ==str2);//False6  7String str1 =NewString ("MyString");8  9String str2 =NewString ("MyString");Ten   OneSystem.out.println (A==B);//False

Two references were created and 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.

For an in-depth understanding, add Example 2:

1  Public classDemo1 {2     3      Public Static voidMain (string[] args) {4         5String str1 = "Hello";6String str2 = "Hello";7String STR3 =NewString ("Hello");8String STR4 =NewString ("Hello");9System.out.println ("Str1==str2?") + (STR1==STR2));//trueTenSystem.out.println ("Str2==str3?") + (STR2==STR3));//false OneSystem.out.println ("Str3==str4?") + (STR3==STR4));//false ASystem.out.println ("Str3.equals (str2)?" + (Str3.equals (STR4)));//true -         //is the string class that overrides the Equals method of object, comparing the contents of the two string objects with consistency.  -         //the "= =" compares the memory address of two objects when comparing data of reference data types, and the Equals method is also the memory address of two objects by default.  the          -TestNULL); -     } -      +}

The principle of implementation is as follows:

The difference between heap memory and stack memory in Java

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.