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:
- The
if
condition is a boolean
expression.
- The
if
and else
clauses can contain a single statement (no braces) or a statement block (surrounded by braces).
- There is no
elseif
clause. However, if
statements may be nested.
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.