三种方法实现变量交换:
public class test3{//三种方法实现变量交换
public static void main(String[] args){
int a = 1 , b = 2 , c = 3 , d = 4 , e = 5 , f = 6;
//以下用不同方法实现变量交换;
//method one
int temp;
temp = a;
a = b;
b = temp;
System.out.println(a+"----"+b);
//method two
c = c + d;
d = c - d;
c = c - d;
System.out.println(c+"----"+d);
//method three
e = e ^ f;
f = e ^ f;
e = e ^ f;
System.out.println(e+"----"+f);
}
}
自增“++”运算符,使用时时应避免的书写方法:
public class test2{//**此代码说明应尽量避免i=i++的写法,如果想用直接i++即可**
public static void main(String[] args){
int i = 10;
i = i++;//**是将i++表达式的值10赋值给i,在执行过程中经历过i=11,但最后此处i被覆盖为10**
System.out.println(i);
i = ++i;
System.out.println(i);
}
}
输出结果如下