classdemo1{ publicstaticvoidmain(String[] args){ int a = 10; int b = 20; System.out.println("交换前:a:"+a+",b:"+b); int c = a; a = b; b = c; System.out.println("交换后:a:"+a+",b:"+b); } }
方式二
用位异或实现(面试用)
classdemo2{ publicstaticvoidmain(String[] args){ int a = 10; int b = 20; System.out.println("交换前:a:"+a+",b:"+b); a = a ^ b; b = a ^ b; // a ^ b ^ b = a a = a ^ b; // a ^ b ^ a = b System.out.println("交换后:a:"+a+",b:"+b); } }
方式三
用变量相加的做法
classdemo3{ publicstaticvoidmain(String[] args){ int a = 10; int b = 20; System.out.println("交换前:a:"+a+",b:"+b); a = a + b; // a=30 b = a - b; // b=10 a = a - b; // a=20 System.out.println("交换后:a:"+a+",b:"+b); } }
方式四
一行代码
classdemo3{ publicstaticvoidmain(String[] args){ int a = 10; int b = 20; System.out.println("交换前:a:"+a+",b:"+b); b = (a+b) - (a=b); // b=30-20=10,a=20 System.out.println("交换后:a:"+a+",b:"+b); } }