Consider below Java program.
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?
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:
- Unbox i to an int value
- Add 1 to that value
- Box the result into another Integer object
- 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
Attention reader! Don’t stop learning now. Get hold of all the important Java and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.
- Wrapper Classes in Java
- Java.Lang.Float class in Java
- Java.lang.Character Class in Java
- Java.lang.Number Class in Java
- Java.lang.Boolean Class in Java
- Java.Lang.Double class in Java
- Java.Lang.Byte class in Java
- Java.Lang.Short class in Java
- Java.lang.Integer class in Java
- Java.Lang.Long class in Java
- Autoboxing and Unboxing in Java
- Base conversion in Java
- Difference between an Integer and int in Java with Examples
- Output of Java programs | Autoboxing and Unboxing