Wrapper classes and call by reference in java

Below is my code:

class Demo{
public static void main(String[] args) {
    Integer i = new Integer(12);

    System.out.println(i);

    modify(i);

    System.out.println(i);

}
private static void modify(Integer i) {

    i= i + 1;
    System.out.println(i);
}

}

EXIT FROM CODE 12 12 but, as I know, we pass the wrapper object “i”, this means that it should be “Call by reference”, then the value should change to 13., but to 12. Someone has appropriate explanation?

+4
source share
5 answers

Links are passed by value, and in addition, Integer immutable .

When passed to the imethod modify, the value of the link is passed (the link is local to this method), and when you assign another object, you only change this local link / variable containing the link. The original remains unchanged.

, , / , .

+7

modify:

    i= i + 1;

Integer, int. :

  • unbox i int
  • 1
  • Integer
  • Integer to i ( i)

, , modify, , modify. , 12 .

, ( , Integer ), mutator . :

class Demo{
    static class IntHolder {
        private int value;
        public IntHolder(int i) {
            value = i;
        }
        public IntHolder add(int i) {
            value += i;
            return this;
        }
        public String toString() {
            return String.valueOf(value);
        }
    }
    public static void main(String[] args) {
        IntHolder i = new IntHolder(12);

        System.out.println(i);

        modify(i);

        System.out.println(i);

    }
    private static void modify(IntHolder i) {

        i.add(1);
        System.out.println(i);
    }

}
+3

- , , , .

, - :

int[] i= new int[1]{12};
...
private static void modify(int[] i) {

    i[0]= i[0] + 1;
    System.out.println(i[0]);
}
+1
0

check my eclipse, it will give the result 12 13 12. The pass-by-value 12 modification method, then i= i + 1;it adds one.

package com.demo.swain;

public class Demo {

        public static void main(String[] args) {
            Integer i = new Integer(12);

            System.out.println(i);

            modify(i);

            System.out.println(i);

        }
        private static void modify(Integer i) {

            i= i + 1;
            System.out.println(i);
        }

        }

Output:12
       13
       12

enter image description here I strongly say that this code does not give output 12, 12.

0
source

All Articles