Does java really handle all primitive types differently than custom Objects? I pose this question as I examined and tried to "interpret" the results of this simple experimental program:
public class RandomObject {
String name;
int value;
public RandomObject(String s, int i){
setName(s);
setValue(i);
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public static void main(String[] args) {
int x = 2;
int y = x;
System.out.println(y);
x = 4;
System.out.println(y);
RandomObject obj1 = new RandomObject("object1", 4);
RandomObject obj2;
obj2 = obj1;
System.out.println(obj2.getValue());
obj1.setValue(17);
System.out.println(obj2.getValue());
}
The results are: 2 2 4 17
Although x has changed, the value of y remains immutable, whereas in objects the change affects both of them. Does the same happen in all primitive types (other than integers) and why?