Conditions

index
BASIC

A condition is a boolean value (or, more accurately, a boolean expression). A boolean value is either true or false.

Boolean values may be stored in boolean variables, but they are most often used as the condition of a loop or if statement.

The simplest type of condition is a boolean literal (true or false). For example:

if (true) {
    System.out.println("This is always printed.");
} 

This isn't very useful. The simplest useful condition is a boolean variable, for example:

if (danger) {
    System.out.println("Run away!");
} 

Of course, this only works if you have previously declared a boolean variable danger and assigned it a value.

More complex boolean expressions can be used as conditions:

if (score < 0 || score > 100) {
    System.out.println("'score' has illegal value: " + score);
} 
STYLE

It is poor style to compare a condition to true or false. For example, if (saved == false) {...} can be shortened to if (!saved) {...}.

It is poor style to use double or triple negatives. For example,

    if (!(cold() || !rainy())) {...}

Long, complicated tests can usually be broken down into a series of more readable tests. If a test is too complicated to be easily understood, it can be made into a boolean method with a descriptive name.