操作符笔记

来源:互联网 发布:js命名规范 编辑:程序博客网 时间:2024/06/07 00:41

  • 取模运算(%)
        int i = 3;//除数        int j = 7;//被除数        int c = i%j;        print(c);//3
当除数小于被除数时,取模的值为除数
        int i = 9;//除数        int j = 7;//被除数        int c = i%j;        print(c);//2
当除数大于或等于被除数,取模值为余数

- 自动递增递减(++,–)

        int j=2;        int l=++j;        System.out.println(l);//3        System.out.println(j);//3        int i=5;        int y = --i;        System.out.println(i);//4        System.out.println(y);//4
符号在前先运算,再赋值
        int n = 3;        int a = n++;        System.out.println(a);//3        System.out.println(n);//4           int v = 6;        int m = v--;        System.out.println(m);//6        System.out.println(v);//5
符号在后先赋值,再运算
  • 逻辑操作符(与&&,或||,非!)
    注:与,或,非只能用于比较布尔值
        int i=2;        int j=3;        boolean flag = (i>j);        System.out.println(flag);//false        System.out.println( (i>0) || (j>4) );//i>0   或者     j>4      返回true        System.out.println( (i>0) && (j>4) );//i>0   与(并且)  j>4      返回false

小结:

        或(||)整个表达式中有一项为true则结果为true        与(&&)整个表达式中有一项为false则结果为false
  • 移位操作
    左移位<<
        value<<num        3 << 2        0000 0000 0000 0000 0000 0000 0000 0011;//3的二进制        0000 0000 0000 0000 0000 0000 0000 1100;//左移2位
value要移位的值,num移动位数,高位舍弃低位补0在数字没有溢出的前提下,对于正数和负数,左移一位都相当于乘以2的1次方,左移n位就相当于乘以2的n次方

右移位>>

        value>>num        35 >> 2        0000 0000 0000 0000 0000 0000 0010 0011;//35的二进制        0000 0000 0000 0000 0000 0000 0000 1000;//右移2位
低位舍弃,高位(value为正数)补0(value为负数)补1右移一位相当于除2,右移n位相当于除以2的n次方

无符号右移>>>

value>>>num
无符号右移的规则只记住一点:忽略了符号位扩展,0补最高位无符号右移规则和右移运算是一样的,只是填充时不管左边的数字是正是负都用0来填充,无符号右移运算只针对负数计算,因为对于正数来说这种运算没有意义无符号右移运算符>>> 只是对32位和64位的值有意义