-2

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?

  • 4
    I don't see any usage of `||` or `|` in your code. Could you share your actual code please? – Mureinik Apr 29 '16 at 11:41
  • i meant & and &&, my bad – TheHoboMaster Apr 29 '16 at 11:42
  • You know that one of them short-circuits. Do you understand what that means? What if your test is `test != null && test.equals("foo")`? Test that. – JB Nizet Apr 29 '16 at 11:44
  • The question pointed to by @JBNizet has an accepted answer that is not correct. Since I can no longer answer this question I cannot fully explain the difference. Suffice it to say that a single & operator is a bitwise and where && is a logical and. Also an `if` statement only evaluates boolean operations. Each part of the if evaluates to a boolean. Then if you bitwise & a boolean with another boolean you will get a boolean result. So in this case you will get the same output. But logical evaluations can short circuit whereas bitwise expressions cannot. – markbernard Apr 29 '16 at 11:58

1 Answers1

0

The main difference is that the && and || operators do some kind of "lazy evaluation"

In this line of code:

method1() & method2();

both methods will be called independant of the return value of method1. On the other hand in this line of code:

method1() && method2();

the method2 will only be called if method1 returns true.

When using || the second method will only be called when the first method returns false.


ParkerHalo
  • 4,341
  • 9
  • 29
  • 51