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
- Wrapper Classes in Java
- Utility methods of Wrapper classes | valueOf(), xxxValue(), parseXxx(), toString()
- Widening Primitive Conversion in Java
- How to get slice of a Primitive Array in Java
- Immutable Map in Java
- Immutable Set in Java
- Is an array a primitive type or an object in Java?
- Comparision of double and float primitive types in Java
- Program to convert Primitive Array to Stream in Java
- Immutable List in Java
- Java: String is Immutable. What exactly is the meaning?
- How to create Immutable class in Java?
- Factory method to create Immutable Set in Java 9
- Factory method to create immutable Map in Java 9
- Factory method to create Immutable List in Java SE 9