if-else Statement

Purpose:

To choose among alternate courses of action in a program.

Mechanics:

if (<condition>) {
/* Java statements */
}
else {
/*other Java statements */
}

Example:

if (numA == numB) {
/* Java statements */
}
else {
/* other Java statements */
}

Usage:

  • <condition> is any expression that evaluates to true or false.

Restrictions:

  • First, the <condition> is evaluated. When the condition evaluates to true, the /* Java statements */ are executed. When the condition evaluates to false, the /* other Java statements */ are executed.
  • If there is more than one Java statement in either clause, then curly brackets are necessary for that clause. Otherwise, the curly brackets are optional.
Back to the Table of Contents
email suggestions to: cs015tas@cs.brown.edu