By Tony Bevis on Tuesday, 10 October 2023
Category: Java

Java programming course: 5.6 Compound operators

In the previous lesson you learnt about logical operators and the if condition:

Compound operators

If you need to test more than one condition at the same time you can use the logical and operator && or the logical or operator ||:

Both above operators only make the second comparison if the first one does not preclude the final result. For example, in the first example above, had i not been less than j then the second comparison of x and y would not have taken place, since it would not affect the final outcome. Similarly, in the second example above, because i is less than j there is no need to test x and y.

Your condition expression may include several compound tests, and you can also include the ! symbol to negate the test:

Java also includes the logical operators & (for and) and | (for or) where they each always test all parts of the comparison, even if it is unnecessary. It is recommended that you use && and || for your comparisons.

If you have methods that return a boolean these can also be used as the conditional expression:

To negate a conditional for a method you can prefix the ! symbol:

In the next lesson you will learn about if...else... blocks.

Next lesson: 5.7 The If...else... block

Related Posts

Leave Comments