I keep seeing the following when I look up why use wrapper classes:
Objects are needed if we wish to modify the arguments passed into a method (because primitive types are passed by value).
- if we set the parameter to the return value we can modify the primitive
- everything in java is passed by value
What does the statement actually mean? Can someone provide an example?
I did a search on why use wrapper classes and came up with the following:
https://www.tutorialspoint.com/why-do-we-need-a-wrapper-class-in-java
https://www.geeksforgeeks.org/need-of-wrapper-classes-in-java/
They all say the same thing. Is it just plain wrong or are they trying to say something else?
CodePudding user response:
Quoted from https://www.tutorialspoint.com/why-do-we-need-a-wrapper-class-in-java:
The objects are necessary if we wish to modify the arguments passed into the method (because primitive types are passed by value).
Quoted from https://www.geeksforgeeks.org/need-of-wrapper-classes-in-java/:
Objects are needed if we wish to modify the arguments passed into a method (because primitive types are passed by value).
Quoted from https://www.javatpoint.com/wrapper-class-in-java:
But, if we convert the primitive value in an object, it will change the original value.
They are indeed just plain wrong in the context of wrappers. The wrapper classes for the primitive types are all immutable, the actual (primitive type) value inside the wrapper cannot be changed once the wrapper object has been created (excluding reflection of course). So even if you have the following code blocks:
Integer outside = Integer.valueOf(42);
someMethod(outside);
and
public static void someMethod(Integer inside) {
}
and the variables outside
and inside
will reference the same object created by Integer.valueOf()
, it will not help you to change the reference value of the outside
variable itself or the object referenced by outside
.
CodePudding user response:
Everything in java is not pass by value, When an Object is passed the reference is passed, hence if you modify the Object in a method and even if the method is not returned, the actuals values of the Object would have been changed after calling the method.