0

I was going through javaTpoint about wrapper class in java and it states that

"Change the value in Method: Java supports only call by value. So, if we pass a primitive value, it will not change the original value. But, if we convert the primitive value in an object, it will change the original value"

Link to article

As first use of wrapper class in java, how can we demonstrate it? I've tried but it didn't worked

Heres my snippet

class demo {
    void change(Integer a) {
        a += 100;
        System.out.println("Value in change: "+a);
    }

    public static void main (String [] a) {
        Integer a = new Integer (10);
        demo obj = new demo();
        System.out.println("Value before change: "+a);
        obj.change(a);
        System.out.println("Value after change: "+a);
    }
}
  • 2
    You can't demonstrate this with `Integer`, because it's immutable. If you wrap the number in some mutable class you can mutate the object you receive instead of just reassigning the variable. The article you linked implies that you can mutate the standard wrapper types, like Integer, which is **incorrect**. – khelwood Sep 14 '20 at 08:56
  • Assignment `=`, which you are doing here, never changes the instance. It only changes the variable. And variables are never _tied to each other_ in Java. So you have to change the actual instance and not just re-assign variables. I.e. `person.setName("Jane")` instead of `person = new Person("Jane");`. – Zabuzard Sep 14 '20 at 08:58
  • 3
    This is either a mistype or the solution to the code: you haven't called the change function after the "value after change" print statement – Robo Mop Sep 14 '20 at 08:58
  • 1
    Does this answer your question? [Is Java "pass-by-reference" or "pass-by-value"?](https://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value) – donquih0te Sep 14 '20 at 09:01
  • 2
    I don't recommend following the tutorials on that site. They're low quality and in many cases even blatantly wrong. – Kayaman Sep 14 '20 at 09:03
  • This code doesn't even compile: the scope of the main method variable a is of type String[]. So you can't redefine it as an Integer. And as @RoboMap already mentioned: the change method is nowhere called. But your question remains valuable as Integer is an object, but is a special one (immutable). see other comments – Conffusion Sep 14 '20 at 09:11
  • @RoboMap it was a typo, after correcting it, im still unable to get required output – Mustafa Shaikh Sep 14 '20 at 09:51

0 Answers0