关于方法传参变量值的问题

public class Test {
	
	void Test(int a,int b) {
		a = a+b;
		b = -b;
	}
	public static void main(String[] args) {
		int a = 1;
		int b = 8;
		Test t = new Test();
		t.Test(a, b);
		System.out.println(a+"  "+b);
	}

}

控制台输出内容为:

1  8
变量a,b参与了运算,但是最后的结果却依然是原值,然后再看下面的代码:

public class Test {
	
	int Test(int a,int b) {
		a = a+b;
		b = -b;
		return a;
	}
	public static void main(String[] args) {
		int a = 1;
		int b = 8;
		Test t = new Test();
		a = t.Test(a, b);
		System.out.println(a+"  "+b);
	}

}

控制台输出内容为:

9  8

综合比较,如果在方法A中声明的变量,然后在方法B中无论作何运算,只要不把A中的变量返回,则A中变量的值依然是原值,如果返回,则变量的值才是参与运算后的值。

发布了61 篇原创文章 · 获赞 9 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/u012129030/article/details/97102687