The values given to the arguments of Java methods are basically passed by value. Passing by value means that the value given to the argument is copied. So if a change is made to an argument in a method, it is making a change to a copy of the argument.
Therefore, you can understand that the movement is as follows.
The easiest program to understand passing by value
int count = 8;
plus(count);
Log.d(count);
void plus(int value) {
int result = value * 2;
Log.d(result);
}
result
after applying plus 16
outside of method plus 8
If you pass a reference type as an argument, the reference value will be copied.
In the code below, the left side is the reference value and the right side is the actual value. The reference value on the left side is, for example, the address of the memory where the actual value on the right side is stored.
List<String> list = new ArrayList<>();
The Imperial Palace is located in 1-1 Chiyoda, Chiyoda-ku, Tokyo
.
1-1, Chiyoda, Chiyoda-ku, Tokyo
is the reference value, and the Imperial Palace is like the actual value.
Based on the above, I would like to consider the following program.
A program in which changes in a method are reflected even after the method is applied
List<String> japanese = new ArrayList<>();
japanese.add("Too much");
plusElementJ(japanese);
Log.d(japanese.toString());
void plusElementJ(List<String> list) {
list.add("Good morning");
Log.d(list.toString());
}
result
[Too much,Good morning]
[Too much,Good morning]
In the above program, the 12th line declares that there is an Imperial Palace in 1-1 Chiyoda, Chiyoda-ku, Tokyo
.
Pass the address of 1-1 Chiyoda, Chiyoda-ku, Tokyo
to the method.
Within the method, we made an extension to the address we received.
Then, even if I went out of the method, I was convinced that there was a result of expanding the Imperial Palace and it in 1-1 Chiyoda, Chiyoda-ku, Tokyo
.
Changes in the method are not reflected after applying the method
String name = "Too much";
concatenate(name);
Log.d(name);
void concatenate(String name) {
name = "Good morning," + name;
Log.d(name);
}
result
after applying concatenate Good morning, too much
outside of method concatenate too
String is a reference type, but immutable. That is, it cannot be changed. Therefore, isn't this process internally creating a new String object as shown below?
name = new String("Good morning," + name)
Therefore, I think the following things are happening.
name
is assigned a new reference valuename
newly references.I can't say it's passed by reference anymore
Recommended Posts