How to Add Buttons and Text to Your JavaFX Project
Java: Negation, Bitwise Not, and Boolean Not
How to Use Comments in Java

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
The Grammar of Java Language
Programming Java: Throwing Errors
Java Programming Challenge: Doing Tic-Tac-Toe as an Applet
How to Run a Canned Java Program
How to Create an Anonymous Class in Java
Advertisement

Inside Dummies.com