Primitive Wrapper Classes are Immutable in Java

1.9

Consider below Java program.

// Java program to demonstrate that prmitive
// wrapper classes are immutable
class Demo
{
    public static void main(String[] args)
    {
        Integer i = new Integer(12);
        System.out.println(i);
        modify(i);
        System.out.println(i);
    }

    private static void modify(Integer i)
    {
        i = i + 1;
    }
}

Output :

12
12

The parameter i is reference in modify and refers to same object as i in main(), but changes made to i are not reflected in main(), why?

Explanation:
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.

The below line of code in the modify method is operating on wrapper class Integer, not an int

i = i + 1;

It does the following:

  1. Unbox i to an int value
  2. Add 1 to that value
  3. Box the result into another Integer object
  4. Assign the resulting Integer to i (thus changing what object i references)

Since object references are passed by value, the action taken in the modify method does not change i that was used as an argument in the call to modify. Thus the main routine still prints 12 after the method returns.

This article is contributed by Yogesh D Doshi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above

GATE CS Corner    Company Wise Coding Practice

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.

Recommended Posts:



1.9 Average Difficulty : 1.9/5.0
Based on 22 vote(s)