4种方式实现两个整数变量的交换

public class TestSwap {
        public static void main(String[] args) {
                int a = 10;
                int b = 20;		
                System.out.println("a:"+a+",b:"+b);
                
                //方式1:使用第三方变量(开发中常用)		
                int c = a;
                a = b;
                b = c;
                System.out.println("a:"+a+",b:"+b);
                System.out.println("------------");		
                
                //方式2:用位异或实现
                //左边:a,b,a
                //右边:a ^ b	
                a = 10;
                b = 20;
                a = a ^ b;
                b = a ^ b; //a ^ b ^ b = a
                a = a ^ b; //a ^ b ^ a = b
                System.out.println("a:"+a+",b:"+b);		
                
                //方式3:用变量相加的做法
                a = 10;
                b = 20;
                a = a + b; //a=30
                b = a - b; //b=10
                a = a - b; //a=20
                System.out.println("a:"+a+",b:"+b);	
                
                //方式4:一句话搞定
                a = 10;
                b = 20;
                b = (a+b) - (a=b); //b=30-20=10,a=20
                System.out.println("a:"+a+",b:"+b);
        }
}

 

你可能感兴趣的:(java)