I thought it was a call-by-reference, but it's called a call-by-value on the Internet. Why?
java parameter-passing pass-by-reference pass-by-value terminology
In Java, we don't use the word call-by-reference. It's all call by value.
Dog myDog;
In , myDog is actually a pointer to a dog, not a dog. What I'm saying is
public void foo(Dog someDog) {
someDog.setName("Max"); // AAA
someDog = new Dog("Fifi"); // BBB
someDog.setName("Rowlf"); // CCC
}
That's the method public static void main(String[] args){ Dog myDog = new Dog("Rover"); foo(myDog);
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." );
}
}
When I said that,
The address pointed to by someDog pointer is 42. If you look at the comment AAA, the name of the contents in address 42 is changed to Max. At this point, the name of myDog changes from main to Max.
If you look at the BBB line, it creates a new dog with the address 70 in someDog. The name of this dog is Fifi and the CCC line replaces the name of the dog at the address 70 with Rowlf.
Did the name of main's myDog change at this time? No. The name of myDog has no longer changed from AAA line to Max.
Java can pass a pointer to the method and change the value of the object that the pointer points to, as in C You cannot change the target that the pointer points to. So Java is Colbyvellian.
© 2024 OneMinuteCode. All rights reserved.