Online Test Banks
Score higher
See Online Test Banks
Learning anything is easy
Browse Online Courses
Mobile Apps
Learning on the go
Explore Mobile Apps
Dummies Store
Shop for books and more
Start Shopping

And Operators (& and &&) in Java

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.

  • Add a Comment
  • Print
  • Share
blog comments powered by Disqus

Inside Sweepstakes

Win $500. Easy.