Control flow statements – if / else if / else

if statement

An if statement checks if a statement evaluates to true. In that case one or more rows of code that follow the if statement is executed.

For example:

In the case above where only one line of code follows the if-statement the braces are not necessary, but it’s a good rule of thumb to always include them. It’s easier to do maintenance on the code if they’re present. Say for example that later you want to add a line of code if the if-statement evaluates to true. If you forget to add the braces then it breaks the logic.

if / else if / else statements

The else if-statement provides an alternative if the if-statement evaluates to false. It checks, like the if-statement, if a certain condition evaluates to true:

The else-statement is where to place code if none of the if- or else if statements evaluates to true. It does not check for any condition to be true and is always placed as the last statement (if used):

The else if-statement can of course be skipped and we can use the if / else statements only:

Search for more Java info on this site here:
Custom Search

Any thoughts or questions?