why wrapper class is immutable


Mutable vs Immutable objects in java

Any object in java is said to be “mutable” if its value can be changed. Immutable objects content can not be changed.

Is String mutable class in java?

No. String is an immutable class in java because we can not change the value of any string object.

What is meant by a wrapper class in java?

In Java, a wrapper class is nothing but a class in which a primitive type value is wrapped up. These primitive wrapper classes are used to represent primitive data types values as objects. For example, Integer is a primitive wrapper class which holds primitive ‘int’ type value. Similarly, Float wrapper objects contain ‘float’ primitive values, Character wrapper class holds a ‘char’, and Boolean wrapper class represents ‘boolean’ primitive type value (true/false).

Are wrapper classes mutable in java?

Once again, a big “No”. Like Strings, primitive wrapper classes in java such as Integer, Float, Long, Byte, Short, and Double are also “immutable” classes. Once created, the numbers wrapped within the objects of wrapper classes in java.lang package can’t be changed.

Example java coding to show that primitive wrapper classes are immutable:

    Line 1:     Integer i = 99;     // Autoboxing (Auto Boxing)
    Line 2:     i = i + 10;         // Unboxing

The above code is written in Java 5 (Java 2 Platform Standard Edition 5.0 or J2SE 5.0 or JDK 1.5). Here we have used a new feature of Java 5 called Autoboxing & Unboxing. Autoboxing is nothing but automatic conversion of primitive type values to wrapper class objects. You can learn more about this autoboxing feature in the tutorial Java 5 (J2SE 5.0/JDK 1.5) New Features with Examples Tutorial. In earlier versions of Java (JDK 1.4 or less), we can write the above code as follows:

                // Integer wrapper class instantiation
    Line 1:     Integer i = new Integer(99);  
    Line 2:     int i2 = i.intValue() + 10;
                i = new Integer(i2);

In either case, JVM creates an Integer object with value 99 and assigns object reference to Integer reference variable ‘i’. In order to add, subtract, or do some other operation on Integer object, first JVM extracts the primitive int value from wrapper object and then performs required operation, in this case addition. Later, the result will be wrapped in a new Integer wrapper object and assigned to Integer reference variable. That means we can’t change the value of wrapper class objects.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s