I have a huge problem to understand why wrapper class in Java doesn't behave like a reference type. Example:
Integer one = 10;
Integer two = one;
one = 20;
System.out.println(one);
System.out.println(two);
The output will be:
20
10
I thought that two
will be 20 like in this example where I create my own class:
class OwnInteger {
private int integer;
public OwnInteger(int integer) {
this.integer = integer;
}
public int getInteger() {
return integer;
}
public void setInteger(int integer) {
this.integer = integer;
}
}
OwnInteger one = new OwnInteger(10);
OwnInteger two = one;
one.setInteger(20);
System.out.println(one.getInteger());
System.out.println(two.getInteger());
So the question, is Integer wrapper class special? Why does it behave as I have shown in my examples?
one = 20;
andone.setInteger(20);
, and it has nothing to do with wrapper classes.one = 20;
of the first snippet would be equivalent toone = new OwnInteger(20);
in the second snippet. – Waftage