java面试之位异或运算符和switch特点

来源:互联网 发布:大数据主要来源于 编辑:程序博客网 时间:2024/05/16 08:48
    a = a^b;        //实现2个数的交换.    b= a^b;//a^b^b =a    a= a^b;//a^a^b =b

可以再数组交换值得时候使用.

int[] arr = { 1, 3, 4, 2, 5, 1 };        // 冒泡排序        for (int i = 0; i < arr.length - 1; i++) {            for (int j = 0; j < arr.length - 1 - i; j++) {                if (arr[j] < arr[j + 1]) {//实现倒着排序,arr[j] < arr[j + 1] 正向排序                      arr[j] = arr[j]^arr[j+1];                      arr[j+1] = arr[j]^arr[j+1];                      arr[j] = arr[j]^arr[j+1];                    /*int temp = arr[j];                    arr[j] = arr[j + 1];                    arr[j + 1] = temp;*/                }            }        }        System.out.println(Arrays.toString(arr));//[5, 4, 3, 2, 1, 1]

最有效率的算出2 * 8的结果 2<<3 意思是2的3次方
8/2 8>>2 意思是8除以2 的2次方


switch语句中的表达式只能是byte,short,char ,int以及枚举(enum),所以当表达式是byte的时候可以隐含转换为int类型,而long字节比int字节多,不能隐式转化为int类型,所以switch语句可以用在byte上而不可以用在long上,另外由于在JDK7.0中引入了新特性,所以witch语句可以接收一个String类型的值,String可以作用在switch语句上

switch 语句 可以省略break , 会出项case 穿透
switch 语句 遇到break 退出,或者是遇到右大括号。
switch 语句 default 可以是任意位置。

int x = 2;        int y = 3;        switch(x){//2            default:                y++;3                break;            case 3:                y++;            case 4:        System.out.println("y="+y);//3

谦虚;见多识广有本领的人,一定谦虚。——谢觉哉定谦虚。——谢觉哉

0 0
原创粉丝点击