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?
答案 0 :(得分:0)
主要区别在于&&
和||
运算符会进行某种“懒惰评估”
在这行代码中:
method1() & method2();
这两种方法都将被称为独立于method1
的返回值。另一方面,在这行代码中:
method1() && method2();
只有在method2
返回method1
时才会调用true
。
使用||
时,只有在第一个方法返回false
时才会调用第二个方法。