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?
Your code fragment does not demonstrate that the wrappers behave like value types: in fact, they are reference types, and they are immutable.
Wrapper classes are used to provide a mechanism to 'wrap' or bind the values of primitive data types into an object. This helps primitives types act like objects and do the activities reserved for objects like we can add these converted types to the collections like ArrayList, HashSet, HashMap, etc.
It is because all primitive wrapper classes (Integer, Byte, Long, Float, Double, Character, Boolean, and Short) are immutable in Java, so operations like addition and subtraction create a new object and not modify the old.
Need of Wrapper ClassesThey convert primitive data types into objects. Objects are needed if we wish to modify the arguments passed into a method (because primitive types are passed by value). The classes in java. util package handles only objects and hence wrapper classes help in this case also.
This is exactly the behavior of a reference type. In your example, two
references the same object as one
after the assignment. However, re-assigning one
a new object has no effect on two
, which is the behavior that you see.
You will see the same behavior with other reference objects as well, for example
StringBuilder one = new StringBuilder("10");
StringBuilder two = one;
one = new StringBuilder("20");
// two still references StringBuilder with "10"
In order for a reference class to exhibit the behavior when changing one object also changes the other, the class needs to be mutable, like the OwnInteger
class in your code, and the code needs to change the object, rather than reassigning it. Wrapper classes, such as Integer
, are immutable, so you would not experience that behavior with them.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With