Incremental Java
Conditions

Conditions

A condition is a Boolean expressions. All control flow constructs use conditions heavily. We're going to look at several conditions that get used a lot.

Has count reached limit?

You'll write code very often where you start an int variable at 0, and count up to, but not including limit, another int variable.

The condition you check is usually: count < limit

Is a number between low and high inclusive?

The condition: num >= low && num <= high.

A common error is to write: low <= num <= high. Relational operators work on two operands at a time. You can't combine them together in this fashion. Fortunately, this causes a compiler error.

Is a number NOT between low and high inclusive?

Just use logical negation on the previous condition: !( num >= low && num <= high ).

Is a number even?

The condition: num % 2 == 0.

The usefulness of the mod operator.

Is a number odd?

The condition: num % 2 == 1.

Also, the condition: num % 2 != 0.

The second condition is basically saying that num is not even.

Is a number divisible by 3, evenly?

The condition: num % 3 == 0.

Notice the similarily with the condition for checking whether a number is even. Testing for evenness is just asking whether a number is divisible by 2 evenly.

Other Examples

I'm sure you can think of many other conditions. One can argue that your ability to program depends very much on your ability to write the condition needed for control flow constructs.