zoukankan      html  css  js  c++  java
  • Java 位运算(移位、位与、或、异或、非)与逻辑运算

    java 位运算包括:左移( << )、右移( >> ) 、无符号右移( >>> ) 、位与( & ) 、位或( | )、位非( ~ )、位异或( ^ ),除了位非( ~ )是一元操作符外,其它的都是二元操作符。

    逻辑运算符&、&&、|、||:

    一、逻辑&与短路&&的区别

    • 总的来说区别是体现在,只有这两个运算符的左边为false的时候会有区别,看如下代码

    1.逻辑&的运算

    boolean a = true;
    boolean b = false;
    int i = 10;
    if(b&(i++)>0)
        System.out.print(i);   //输出11,即&的右边有进行运算
    else
        System.out.print(i);

    2.短路&&的运算

    boolean a = true;
    boolean b = false;
    int i = 10;
    if(b&&(i1++)>0)
        System.out.print(i);   //输出10,即&&的右边没有运算
    else
        System.out.print(i);

    小结一下: 
    &:不管&的左边是true还是false,右边都会进行运算 
    &&: 只要左边是false,右边就不会进行运算 
    一半情况下都会选择&&,因为这样可以提高效率,也可以进行异常处理,当右边产生异常的时候,同样可以跳过。

    二、逻辑| 与短路||的区别

    • 和上面的类似,只不过这两者是只有当左边为true的时候,才会有区别,看如下代码

    1.逻辑 | 的的运算

    boolean a = true;
    int i = 10;
    if(a|(i++)>0)
        System.out.print(i);   //输出11,即的右边有进行运算
    else
        System.out.print(i);

    2.短路 || 的运算

    boolean a = true;
    int i = 10;
    if(a||(i++)>0)
        System.out.print(i);   //输出10,即||的右边没有运算
    else
        System.out.print(i);

    小结: 
    | : 当左边为true时,右边同样进行运算 
    || : 当左边为true时,右边不再进行运算

  • 相关阅读:
    清北学堂 清北-Day1-R1-Count
    清北学堂 清北-Day1-R2-监听monitor
    LuoGu P2420 让我们异或吧
    Milk(sort+结构体)
    开门人和关门人(结构体+sort)
    python-神奇的下划线
    python-pathlib
    python-文本字符串
    python-闭包
    进制-Iterative-进制转换
  • 原文地址:https://www.cnblogs.com/lordcheng/p/7609423.html
Copyright © 2011-2022 走看看