And Operators (& and &&)

Java has two operators for performing logical And operations: & and &&. Both combine two Boolean expressions and return true only if both expressions are true.

Here’s an example that uses the basic And operator (&):

if ( (salesClass == 1) & (salesTotal >= 10000.0) )

commissionRate = 0.025;

Here, the expressions (salesClass == 1) and (salesTotal >= 10000.0) are evaluated separately. Then the & operator compares the results. If they’re both true, the & operator returns true. If one is false or both are false, the & operator returns false.

tip.eps Notice that I use parentheses to clarify where one expression ends and another begins. Using parentheses isn’t always necessary, but when you use logical operators, I suggest that you always use parentheses to clearly identify the expressions being compared.

The && operator is similar to the & operator, but can make your code a bit more efficient. Because both expressions compared by the & operator must be true for the entire expression to be true, there’s no reason to evaluate the second expression if the first one returns false. The & operator always evaluates both expressions. The && operator evaluates the second expression only if the first expression is true.

Get Java For Dummies Quick Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.