Java – pass reference type variables as method parameters

After running the following code, I get this output:

Who can explain why the value of a variable of type person is changed and the value of a variable of type integer is not? I've 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 people and integers work differently

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"; 
    }
}

Solution

In Java, primitive types (such as integers) are always handled exclusively by values, and objects (such as your person) and arrays are always handled exclusively by reference

If the primitive is passed, the value is copied, and if the reference type is passed, the address is copied, so there is a difference

If you follow the links above and / or do some Googling 'you will find more

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>