Passing reference type variables as a method parameter

After running the code below, I get this output: Eva 1200

Can someone explain to me why the value of a variable of type Person changes, but the value of a variable of type Integer does not? I already read this:

  • www.javaworld.com/javaworld/javaqa/2000-05/03-qa-0526-pass.html
  • www.yoda.arachsys.com/java/passing.html#formal

but I don’t understand why it works differently with Person and Integer types.

public class Test {
    public static void main(String[] args) {
        Object person = new Person("Adam");
        Object integer = new Integer("1200");

        changePerson(person);
        changeInteger(integer);

        System.out.println(person);
        System.out.println(integer);
    }

    private static void changeInteger(Object integer) {
        integer = 1000;
    }

    private static void changePerson(Object person) {
        ((Person)person).name="Eve"; 
    }
}
+3
source share
7 answers

In Java, primitive types (such as integer) are always processed exclusively by value, and objects (for example, your Person) and arrays are always processed exclusively by reference .

, , , , , .

/ googlin ', .

+2

Integer ( ). Person . .

+2

changeInteger(), integer = 1000, .

person = new Person();
person.name="Eve";

in changePerson()

, .

PS: , .

+1

, ( , ). OP . , , . , . , (.. , ) , . Java, , . , . , , , , . , integer = 1000, Integer - .

, Integer (, .setValue()), , Integer.

+1

? .

private static void changeInteger(Object integer) {
    integer = 1000;
}

integer , object, . Person.

:

. Java . get . name Person. Person Person, name . , .

0

changeInteger() (1000) integer. integer main() (1200). , print() main() (1200)

changePerson() person . , .

Aslo, , Integer ( ) . , ref var, JDK .

, !

0

In changePerson (), you yourself modify this object using its public name property. In changeInteger () you change the local Integer object,

Place the file System.out.println (integer); inside the function changeInteger (), and you will see that Integer is changing, but only in the function area.

private static void changeInteger(Object integer) {
    integer = 1000;
    System.out.println(integer);
}
0
source

Source: https://habr.com/ru/post/1730622/


All Articles