JAVA: What is the difference between a logical AND/OR and short circuit AND/OR?

时间:2016-04-29 11:39:40

标签: java conditional statements

When I run a simple program, both of them ( & and && ) seem to work interchangeably. Could someone please explain when I should use each case?

 public class Test1 {

    public static void main(String [] args){

        int counter = 0;

        int dice1;
        int dice2;


    for (int loop = 0; loop <= 1000; loop++) {


    dice1= (int) (Math.random()*6)+1;
    dice2= (int) (Math.random()*6)+1;

        if (dice1 == 6 && dice2 == 6){
            counter ++;
        }

    }

    System.out.println("Counter = " + counter);

    } 
}

This program also seems to work when I use & instead of &&. So what's the difference?

1 个答案:

答案 0 :(得分:0)

主要区别在于&&||运算符会进行某种“懒惰评估”

在这行代码中:

method1() & method2();

这两种方法都将被称为独立于method1的返回值。另一方面,在这行代码中:

method1() && method2();

只有在method2返回method1时才会调用true

使用||时,只有在第一个方法返回false时才会调用第二个方法。