-3
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package corejava;

/**
 *
 * @author Administrator
 */
public class CoreJava {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        Test test=new Test();
        test.setx(20);
        test.printx();

        Test test1=test;
        test1.setx(40);
        test1.printx();
        test.printx();


        int a=20;
        int b=a;
        a=40;
        System.out.println(a);
        System.out.println(b);

    }
}

Output:

run:
X is 20
X is 40
X is 40
40
20

Now here when i set the value of 'x' in 'a' and assigned the object 'a' to 'b', 'b' will point to the same value of object 'a'. so any changes to 'a' will also change the value of 'b';

But when i used simple variables why didn't it do the same as for objects. Why the objects stored in heap and variables in stack area.

trincot
  • 317,000
  • 35
  • 244
  • 286
Maclean Pinto
  • 1,075
  • 2
  • 17
  • 39

2 Answers2

4

This has nothing to do with heap vs stack, and everything to do with assignment semantics of primitives vs reference types.

Object assignment in Java does not copy, so Test test1=test; just creates another "name" (another variable) which refers to the same object in memory.

Primitive assignment does copy, so int b=a creates a second int with the same value, which is independent from the first afterward.

Matt Ball
  • 354,903
  • 100
  • 647
  • 710
1

Java only stores primitives (what you call variables) on the stack. Objects are created on the heap, and only references (which in turn are primitives) are passed around on the stack.

The main difference between stack and heap is the life cycle of the values. Stack values only exist within the scope of the function they are created in. Once it returns, they are discarded. Heap values however exist on the heap. They are created at some point in time, and destructed at another (either by GC or manually, depending on the language/runtime).

Zycho
  • 298
  • 3
  • 13