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

Nish Grewal :

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"

gtgaxiola :

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))    

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=152532&siteId=1
Recommended