The difference between Java Heap and Stack is that heapstack

Source: Internet
Author: User

The difference between Java Heap and Stack is that heapstack

Heap in Java is a runtime data zone used to store class objects; Stack) it mainly stores basic data types (int, char, double, and other 8 basic data types) and object handles.

Example 1

Int a = 5; int B = 5; System. out. println (a = B );

In the above example, the compiler first processes int a = 5, first creates a reference a in the stack, and then searches for the value of 5 in the stack. If yes, point a to 5. If no, create a 5 and then point a to 5. When processing int B = 5, because the stack must already have 5, direct B to 5, so that both a and B point to 5, so a = B is true.

Example 2

Int a = 5; int B = 5; System. out. println (a = B); B = 6; System. out. println (a = B );

In the preceding example, after a value is assigned to B, a and B do not point to the same value. Therefore, the first a = B is true, and the second a = B is false.

Example 3

String a = "ABC"; String B = "ABC"; String c = new String ("ABC"); String d = new String ("ABC"); System. out. println (a = B); System. out. println (a = c); System. out. println (c = d );

In the above example, String is an object. Therefore, it is stored in the heap. The process of assigning values to a and B is similar to that of Example 1, but it is only carried out in the heap. C and d use the new Keyword. Therefore, no matter whether the value exists in the heap or not, a new value is created in the heap. Therefore, the output result is true, false, or false.

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.