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

相关文章:

  • 2021-05-29
  • 2022-12-23
  • 2022-01-22
  • 2021-05-19
  • 2021-07-12
  • 2022-12-23
猜你喜欢
  • 2021-12-18
  • 2022-01-17
  • 2022-12-23
  • 2022-12-23
  • 2021-11-02
相关资源
相似解决方案