短路与和与、短路或和或的区别

&&(短路与)与&的区别:

  • 最终结果都是一样的
  • &&具有短路的效果。左边是false,右边就不执行

      int x1 = 3;
      int y1 = 4;
      System.out.println((++x1 == 3) & (++y1 == 4)); //false & false = false
      System.out.println("x1 = " + x1);     //x1 = 4
      System.out.println("y 1= " + y1);     //y1 = 5
    
      int x2 = 3;
      int y2 = 4;
      System.out.println((++x2 == 3) && (++y2 == 4)); //false & false = false
      System.out.println("x2 = " + x2);     //x2 = 4
      System.out.println("y2 = " + y2);     //y2 = 4
    

||(短路或)与|的区别:

  • 最终的效果都是一样的
  • ||具有短路的效果,左边为true,右边不执行

      int x1 = 3;
      int y1 = 4;
      System.out.println((++x1 == 3) | (++y1 == 4)); //false & false = false
      System.out.println("x1 = " + x1);     //x1 = 4
      System.out.println("y 1= " + y1);     //y1 = 5
    
      int x2 = 3;
      int y2 = 4;
      System.out.println((++x2 == 3) || (++y2 == 4)); //false & false = false
      System.out.println("x2 = " + x2);     //x2 = 4
      System.out.println("y2 = " + y2);     //y2 = 5
    
      int x3 = 3;
      int y3 = 4;
      System.out.println((++x3 == 4) || (++y3 == 4)); //true & false = true
      System.out.println("x3 = " + x3);     //x3 = 4
      System.out.println("y3 = " + y3);     //y3 = 4
    

你可能感兴趣的:(Java)