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
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");
}
© 2024 OneMinuteCode. All rights reserved.