// Class definition
class Thing {
int x; // instance variable
public Thing(int i) { x = i; } // constructor method
}
// Driver
public class CopyDemo {
public static void main(String[] argv) {
// Primitive variables
int i = 0, j = 1;
System.out.println("1. i is " + i + " j is " + j +
" i == j is " + (i == j));
j = i; // assign primitive variable
System.out.println("2. i is " + i + " j is " + j +
" i == j is " + (i == j));
i = i + 1; // note j does not change
System.out.println("3. i is " + i + " j is " + j +
" i == j is " + (i == j));
j = j + 1;
System.out.println("4. i is " + i + " j is " + j +
" i == j is " + (i == j));
// Reference variables
Thing a = new Thing(0); Thing b = new Thing(1);
System.out.println("5. a.x is " + a.x + " b.x is " + b.x +
" a == b is " + (a == b));
b = a; // assign reference variable
System.out.println("6. a.x is " + a.x + " b.x is " + b.x +
" a == b is " + (a == b));
a.x = a.x + 1; // note b.x also changes
System.out.println("7. a.x is " + a.x + " b.x is " + b.x +
" a == b is " + (a == b));
Thing c = new Thing(1); // but a and c are not ==
System.out.println("8. a.x is " + a.x + " c.x is " + c.x +
" a == c is " + (a == c));
}
}
-----------------
$ java CopyDemo
1. i is 0 j is 1 i == j is false
2. i is 0 j is 0 i == j is true
3. i is 1 j is 0 i == j is false
4. i is 1 j is 1 i == j is true
5. a.x is 0 b.x is 1 a == b is false
6. a.x is 0 b.x is 0 a == b is true
7. a.x is 1 b.x is 1 a == b is true
8. a.x is 1 c.x is 1 a == c is false