Home

And Operators (& and &&) in Java

|
|  Updated:  
2016-03-26 16:03:28
|   From The Book:  
No items found.
Java Essentials For Dummies
Explore Book
Buy On Amazon

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.

Notice the use of parentheses to clarify where one expression ends and another begins. Using parentheses isn’t always necessary, but when you use logical operators, it’s a good idea to 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.

About This Article

This article is from the book: 

No items found.

About the book author:

Doug Lowe is the information technology director at Blair, Church & Flynn Consulting Engineers, a civil engineering firm. He has written more than 50 For Dummies books on topics ranging from Java to electronics to PowerPoint.