javawrapper

Java wrapper classes - change value of parameters


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).

  1. if we set the parameter to the return value we can modify the primitive
  2. 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:

  1. https://www.tutorialspoint.com/why-do-we-need-a-wrapper-class-in-java

  2. https://www.geeksforgeeks.org/need-of-wrapper-classes-in-java/

  3. https://www.javatpoint.com/wrapper-class-in-java

They all say the same thing. Is it just plain wrong or are they trying to say something else?


Solution

  • 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.