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