Back

Control Flow

Reading

A real decision is measured by the fact that you've taken a new action. If there's no action, you haven't truly decided. [Tony Robbins]

Boolean expressions

Boolean expressions are statements that can one of two values: true or false.

Example:
100 > 50 -> evaluates to true

Boolean Operators

  • !
  • &&
  • ||
  • >
  • >=
  • <=
  • <
  • !=
  • ==
  • negation
  • and (conjunction)
  • or (disjunction)
  • greater than
  • greater than or equal to
  • less than or equal to
  • less than
  • not equal
  • equal NOTE the difference between "=", which is the assignment operator
Boolean expressions evaluate to true or false.

if statements

if statements are used to allow your code to follow different paths depending on a condition.

The concept: if the statement is true, do the following bit of code.

The basic pattern:
if ( boolean expression ) { code to be executed }

Else

If the expression we check is not true, a different set of instructions can be used.

A concrete example:

We have a few more forms:

This shows an else if. It requires a second condition to be checked before moving on. In fact, you can chain else if's together to check a series of different condition making it work just like a switch (with more typing).

if else statements use a boolean expression to determine which code to execute.

Nested If Statements

Now just to give you more control, you can put an if any place where you can put statements.

if statements can be nested to deal with sub conditions.
You can put an if statement anywhere you can put a set of statements: method, loop, if, where ever it is needed.

Switch

switch is a shortcut to using a long series of if-else statements
You can only switch on ints, bytes, shorts, chars. You cannot use strings.

To use switch you define a number of cases, and a default case. Once the case has been completed you break out of the block.

Basic Switch

A real world example

You must always have a default case.
You cannot switch on string values.