I would like to understand how primitive and object reference variable behaves differently. I have used the below code from OCA/OCP Java SE7 by Kathy Sierra as an example:
public class VariableTesting {
public static void main(String[] args) {
int a = 10;
System.out.println("a= " + a);
int b = a;
b = 30;
System.out.println("a= " + a + " after change it to b and b is " + b);
Dimension a1 = new Dimension(5, 10);
System.out.println("a1.height = " + a1.height);
Dimension b1 = a1;
b1.height = 30;
System.out.println("a1.height= " + a1.height + " after change to b1");
}
}
In the above piece of code, I'm getting the value of a = 10; before and after changing the value of b.
The output for the primitive variable case is:
a = 10
a = 10 after change it to b and b is 30
However, in object reference variable I'm getting a different value once I change the value of b1.height = 30;
The output for the reference variable case is:
a1.height = 10
a1.height = 30 after change to b1
It is mentioned in the book that in both case the bit pattern is copied and a new copy is placed. If this is true, then why we are getting different behavior?