Java交换两个数的方法

方法一,引入第三方变量

public class Mock {

	public static void main(String[] args) {
		int a = 20;
		int b = 10;
		int temp = 0;
		System.out.println("交换前:"+"a="+a+"\t"+ "b="+b);
		temp = a;
		a = b;
		b = temp;
		System.out.println("交换后:"+"a="+a+"\t"+ "b="+b);


	}

}

方法二,不引入第三方变量

public class Mock {

	public static void main(String[] args) {
		int a = 20;
		int b = 10;
		System.out.println("交换前:"+"a="+a+"\t"+ "b="+b);
		a = a + b;
		b = a - b;
		a = a - b;
		System.out.println("交换后:"+"a="+a+"\t"+ "b="+b);


	}

}

方法三,不引入第三方变量

public class Mock {

	public static void main(String[] args) {
		int a = 20;
		int b = 10;

		System.out.println("交换前:"+"a="+a+"\t"+ "b="+b);
		a = a ^ b;
		b = a ^ b;
		a = a ^ b;
		System.out.println("交换后:"+"a="+a+"\t"+ "b="+b);


	}

}

 

你可能感兴趣的:(Java学习)