Java中参数始终是按值传递。
public class Main {
public static void main(String[] args) {
int x = 5;
change(x);
System.out.println(x);
}
public static void change(int x) {
x = 10;
}
}
5
public class Main {
public static void swap(Integer i, Integer j) {
Integer temp = new Integer(i);
i = j;
j = temp;
}
public static void main(String[] args) {
Integer i = new Integer(10);
Integer j = new Integer(20);
swap(i, j);
System.out.println("i = " + i + ", j = " + j);
}
}
i = 10, j = 20
class Test {
int x;
Test(int i) {
x = i;
}
Test() {
x = 0;
}
}
public class Main {
public static void main(String[] args) {
Test t = new Test(5);
change(t);
System.out.println(t.x);
}
public static void change(Test t) {
t = new Test();
t.x = 10;
}
}
5
class Test {
int x;
Test(int i) {
x = i;
}
Test() {
x = 0;
}
}
public class Main {
public static void main(String[] args) {
Test t = new Test(5);
change(t);
System.out.println(t.x);
}
public static void change(Test t) {
t.x = 10;
}
}
10