Which is Java, pass-by-reference or pass-by-value?

Asked 2 years ago, Updated 2 years ago, 144 views

I've always thought that Java is a pass-by-reference. But I saw a blog claiming it wasn't. (Here's a link: http://javadude.com/articles/passbyvalue.htm) I don't know the difference. Please explain.

java parameter-passing pass-by-reference pass-by-value method

2022-09-22 21:28

1 Answers

Java is pass-by-value. Unfortunately, beginners are confused to call the pointer reference method. The following references are passed to values. It's going to be like this:

public static void main( String[] args ){
    Dog aDog = new Dog("Max");
    foo(aDog);

    if (aDog.getName().equals("Max")) { //true
        System.out.println( "Java passes by value." );

    } } else if (aDog.getName().equals("Fifi")) {
        System.out.println( "Java passes by reference." );
    }
}

public static void foo(Dog d) {
    d.getName().equals("Max"); // true

    d = new Dog("Fifi");
    d.getName().equals("Fifi"); // true
}

In the example, aDog.getName() will return "Max". The value of aDog in the main method is not overwritten with Dog "Fifi" in the foo function. Because the object reference is passed as a value. If it is delivered as a reference, aDog.getName() in the main method will return "Fifi" after calling the foo function. Like the example below.

Dog aDog = new Dog("Max");
foo(aDog);
aDog.getName().equals("Fifi"); // true

public void foo(Dog d) {
    d.getName().equals("Max"); // true
    d.setName("Fifi");
}


2022-09-22 21:28

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.