Java实现变量交换的两种方法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Point9/article/details/83547651

方法一:引入第三方变量


public class ChangeVar{
	public static void main(String[] args){
		//交换变量
		 int a = 1;
		int b = 2;
		int c= a; //1
		a = b;//2
		b = c; //1
        System.out.println(a);//2
		System.out.println(b);//1
	}
}

方法二:通过算术运算符实现


public class ChangeVar{
	public static void main(String[] args){
		//交换变量
		int a = 1;
		int b = 2;
		a = a+b;//3
		b = a-b;//1
		a = a-b;//2
        System.out.println(a);//2
		System.out.println(b);//1
	}
}

Web全栈技术交流

点击链接加入群聊【Web全栈交流群】:https://jq.qq.com/?_wv=1027&k=5rnUzsF

QQ群二维码

 

猜你喜欢

转载自blog.csdn.net/Point9/article/details/83547651