Java Interview questions: Heap memory and Stack memory

Source: Internet
Author: User

Java divides memory into two types: one is stack memory and heap memory

Some basic types of variables and object reference variables defined in the function are allocated in the stack memory, and when a variable is defined in a block of code, Java allocates memory space for the variable in the stack, and when the scope of the variable is exceeded, Java automatically frees the allocated memory space for that variable. The memory space can be used for other purposes immediately.

Heap memory is used to hold objects and arrays created by new, and the memory allocated in the heap is managed by the JVM (Java Virtual machine) 's automatic garbage collector, and after an array or object is produced in the heap, a special variable can be defined in the stack. Make the value of this variable in the stack 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 the name of an array or object, and you can use reference variables from the stack in your program to access the arrays or objects in the heap.

Specifically:

Stacks and heaps are places where Java is used to store data in RAM, unlike C + +, where 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 the objects of the class allocate space. These objects are established through directives such as new, NewArray, Anewarray, Multianewarray, and they do not require program code to be explicitly released. The heap is responsible for the garbage collector, 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 primarily holds variables of a primitive type (byte, short, int, long, float, double, char, Boolean) and object handle (reference variable).

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 first 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 not found, stores 3 in it and points a to 3. Then deal with int b = 3; , after creating the reference variable for B, because there are already 3 values in the stack, point B directly to 3. In this case, A and B both point to 3. At this point, if you make a = 4, then the compiler will re-search the stack for a value of 4, if not, the 4 will be stored in, and a point to 4, if already, then direct a to the address. Therefore the change of a value does not affect the B value. 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 that can be used:

String str = new String ("abc");

String str = "ABC";

Two forms to create, the first is to use new () to create the object, it will be stored in the heap, each call will create a new object, and the second is to create a string class in the Stack object reference variable str, and then find whether the stack is stored "ABC", if not, then "ABC" Store the stack and make str point to "ABC", and if it already has "ABC", direct str to "ABC".

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 point to the same object

String str1 = new String ("abc");

String str2 = new String ("abc");

System.out.println (str1 = = str2); False

With new, a different object is generated, and each invocation generates a new object.

So create multiple "abc" strings in the second way (string str = "abc";) and store only one object in memory. This is useful for saving memory space, and it can improve the speed of the program to some extent, because the JVM (Java Virtual machine) automatically determines whether it is necessary to create new objects based on the actual facts of the data in the stack. and for string str = new String ("abc"); Code, it is necessary to create new objects in the heap, regardless of whether their string values are equal, to create new objects, thereby aggravating the burden of the program.

On the other hand, be aware that:

when creating an object using a format such as String str = "ABC", we always want to assume that the object of the string class was created STR, beware of traps, objects may not be created! Instead, it might just point to a previously created object. only through the new () method can you guarantee that a new object is created each time. Because of the immutable (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.

Example:

String a = "abc";

String B = "abc";

String c = new String ("abc");

String d = C.intern ();

How many objects does this code create altogether?

Java Interview questions: Heap memory and Stack memory

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.