Search code examples
javalogiccomparisonand-operator

Does using a parenthesis make a difference when using && or ||?


Is one preferred over the other? If so, why?

 int value1 = 1;
 int value2 = 2;

 if (value1 == 1 && value2 == 2) {
    System.out.println("works");
    }

 if ((value1 == 1) && (value2 == 2)) {
    System.out.println("works");
    }

Expected matches actual results. Both print the string "works"


Solution

  • Parentheses are useful to group your logical expressions just as you would in a mathematical expression.

    It makes the order of precedence clearer.

    In this case they are not needed as you are working with only 2 expressions.

    But what happens on a similar case using both OR and AND?

    It can lead to an ambiguous case:

    if (a && b || c)
    

    Will be interpreted as:

    if ((a && b) || c)
    

    When you wanted the expression to be treated as:

    if (a && (b || c))