The difference between the heap and stack (stack) of Java

Source: Internet
Author: User

The heap in Java is a run-time data area that holds the objects of a class, and the stack (stack) primarily holds basic data types (8 basic data types, int, char, double, etc.) and object handles.

Example 1

        int a=5;         int b=5;        System.out.println (a==b);

In the example above, the compiler first processes int a=5, first creating a reference a in the stack, then looking in the stack for a value of 5, and if so, a to 5, if not, a 5, and a to 5. When working with int b=5, because there must already be 5 in the stack, point B directly 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 above example, after assigning a value to B, a and b do not point to the same value, so 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 example above, string is an object, so it is stored in the heap, and the procedure for assigning A and B is similar to Example 1, except in the heap. C and D use the keyword new so that no matter whether the value is equal, a new value is created in the heap, so the output is true,false,false.

The difference between the heap and stack (stack) of 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.