Please look at the following code :
public static void main(String[] args) {
Random random = new Random();
int[] array = new int[10];
Arrays.setAll(array, operand -> random.nextInt(10));
System.out.println(Arrays.toString(array));
swap(array, 0, 9);
System.out.println(Arrays.toString(array));
}
static void swap(int[] array, int i, int j) {
int temp = array[i]; // pass by value ??
array[i] = array[j]; // the value of temp doesn't change, why?
array[j] = temp; // temp == array[i]
}
What exactly happens in the method swap
?
I need a full explanation and a low level.
EDIT :
OK, let me show you another example :
public class StringHolder {
private String value;
public StringHolder(String value) {
this.value = value;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
@Override
public String toString() {
return getValue();
}
}
main method :
public static void main(String[] args) {
StringHolder[] holders = new StringHolder[]{new StringHolder("string 1")};
StringHolder tmp = holders[0];
holders[0].setValue("string 2");
System.out.println(tmp);
System.out.println(holders[0]);
}
output :
string 2
string 2
According to @chokdee's answer, tmp
is a new variable and have it's own piece of memory...
but when we apply changes to the original variable (holder[0]
), it also affects tmp
.
another example :
public static void main(String[] args) {
StringHolder[] holders = new StringHolder[]{new StringHolder("string 1")};
StringHolder tmp = holders[0];
holders[0] = new StringHolder("string 2");
System.out.println(tmp);
System.out.println(holders[0]);
}
output :
string 1
string 2
Thanks in advance.