Java Programming/Conditional blocks

Conditional blocks allow a program to take a different path depending on some condition(s). These allow a program to perform a test and then take action based on the result of that test. In the code sections, the actually executed code lines will be highlighted.

If
The block executes only if the boolean expression associated with it is true. The structure of an  block is as follows:

Here is a double example to illustrate what happens if the condition is true and if the condition is false:

If/else
The  block may optionally be followed by an  block which will execute if that boolean expression is false. The structure of an  block is as follows:

If/else-if/else
An  block may be used when multiple conditions need to be checked. statements come after the  block, but before the   block. The structure of an  block is as follows:

Here is an example to illustrate:

Keep in mind that only a single block will execute, and it will be the first true condition.

All the conditions are evaluated when  is reached, no matter what the result of the condition is, after the execution of the   block:

Conditional expressions
Conditional expressions use the compound  operator. Syntax:

This evaluates, and if it is   then the conditional expression has the value of  ; otherwise the conditional expression has the value of.

Example:

This is equivalent to the following code fragment:

Switch
The conditional statement is basically a shorthand version of writing many ... statements. The block evaluates a, , , or  (or , starting in J2SE 5.0; or , starting in J2SE 7.0), and, based on the value provided, jumps to a specific  within the switch block and executes code until the  command is encountered or the end of the block. If the switch value does not match any of the case values, execution will jump to the optional case.

The structure of a  statement is as follows:

Here is an example to illustrate:

If a case does not end with the  statement, then the next case will be checked, otherwise the execution will jump to the end of the   statement.

Look at this example to see how it's done:

Starting in J2SE 5.0, the  statement can also be used with an  value instead of an integer.

Though  have not been covered yet, here is an example so you can see how it's done (note that the enum constants in the cases do not need to be qualified with the type:

Starting in J2SE 7.0, the  statement can also be used with an  value instead of an integer.