Head first Java writes that "Java is passed by value, that is, through a copy," which concludes that the method cannot change the parameters passed in by the caller. How do you understand that?
See Example:
public class Test1 {
public static void Main (string[] args) {
int x = 7;
System.out.println ("Before incoming method: x=" +x);
AddOne (x);
System.out.println ("After incoming method: x=" +x);
}
private static void AddOne (int y) {
y++;
SYSTEM.OUT.PRINTLN ("Incoming parameter changed: y=" +y);
}
}
Output:
Before passing in method: X=7
The incoming parameter was changed: Y=8
After passing in method: X=7
Because the method changes only the copy of the value (the value of the variable y), it has no effect on the original value (the value of the variable x). So the value of X is 7 before and after the method being passed in.
So look at the following example
public class Dog {
String name;
int age;
Omit Get,set
}
public class Test2 {
public static void Main (string[] args) {
Dog yellow = new Dog ();
Yellow.setname ("rhubarb");
System.out.println ("Before incoming method: Yellow's name is" +yellow.getname ());
ChangeName (yellow);
System.out.println ("After the method passed: Yellow's name is" +yellow.getname ());
}
private static void ChangeName (Dog white) {
White.setname ("small white");
System.out.println ("the incoming parameter is changed: White's name is" +white.getname ());
}
}
Before passing in method: Yellow's name is rhubarb
The incoming parameter is changed: White's name is small
After the method is passed in: Yellow's name is small white
Yellow's name before being passed into the method is "rhubarb", after passing into the method has become "small white", then "the method cannot change the parameters of the caller passed" The argument is still valid?
The answer is yes.
The difference between the Dog yellow and int i is that int i is the primitive main data type variable and the value of the variable is 7, so the value copied to Y is the 7,addone method before and after X is always equal to 7. The former is an object reference variable (yellow is the bit notation for getting the dog object, known as a pointer), so the copy to dog White is just a pointer, and yellow and white point to the same dog object in the heap memory. The ChangeName method changes the value of the instance variable name of the dog object that is pointed to, but the yellow pointer always points to the dog object, and the value passed in (the pointer) has not changed.
Java is passed by value, that is, through copy transfer--by means of manipulating different types of variables to deepen understanding