Control Flow  «Prev  Next»


Lesson 3Decision Making Statements
ObjectiveCover Important Points about the if and switch Statements

Java Decision Making Code

Java if statement

The if[1] statement is common to almost all high-level programming languages. It evaluates a boolean expression (called the if condition) and executes a designated statement block if the expression evaluates to true. Important points that you should remember about the if statement are:
  1. The if condition is a boolean expression.
  2. The if and else clauses can contain a single statement (no braces) or a statement block (surrounded by braces).
  3. There is no elseif clause. However, if statements may be nested.

if (condition) {
  /* Statement(s) that are executed if the
  condition is true */
}
else {
  /* Statement(s) that are executed if the
  condition is false */
}

Java Language Reference

The switch Statement

The switch statement is similar to the if statement in that it evaluates an expression to determine which statement block should be executed next. However, the switch statement is different in that it evaluates an int expression instead of a boolean expression. The other difference is that the cases of the switch statement are not mutually exclusive[2]. If a case does not end in a break statement, then execution continues with the next statement.
The case clauses of the switch statement must evaluate to an int value after numeric promotion. This means that you can only use byte, char, short, and int expressions in the case clauses. The default clause of the switch statement is optional. If it is present, it serves as the case that is executed if no other cases are matched.

switch (intExpression) {
  case n1:
    /* Statement(s) that are executed if the
    expression evaluates to n1. */
  case n2:
    /* Statement(s) that are executed if the
    expression evaluates to n2. */
  case n3:
    /* Statement(s) that are executed if the
    expression evaluates to n3. */
  default:
    /* Statement(s) that are executed if no
    other case is matched. */ }

[1] If condition: The condition that is evaluated as part of an if statement.
[2] Mutually exclusive: Either but not both. Exclusive OR is known as the "symmetric difference of sets".