  Conditional Statements

The "if" conditional

The "if" conditional in Java will perform some specified action (or set of actions) only if a given condition is met.

Syntax for an "if" statement

if (booleanExpression) {
statement(s);          //only executed if booleanExpression is true
}

Example

• Testing whether a number is even or odd:
if (number % 2 == 0) {
System.out.println(number + " is even");
}
if (number % 2 != 0) {
System.out.println(number + " is odd");
}

Be careful, the parentheses around the booleanExpression condition are required!

if (i > 0) && (i < 10) {
int a = 10;
a = a / 3;
System.out.println("i is between 0 and 10");
}

GOOD:

if ((i > 0) && (i < 10)) {
int a = 10;
a = a / 3;
System.out.println("i is between 0 and 10");
}

Block statements

The if statement will execute the first statement after its condition. If more than one statement needs to be executed if the condition is true, then these statements should be wrapped into a block statement by enclosing these statements with curly braces.

THIS...

The following examples work identically

if ((i > 10) && (i < 10)) {
System.out.println("i is between 0 and 10");
}

IS THE SAME AS...

if ((i > 10) && (i < 10))
System.out.println("i is between 0 and 10");

However, notice the following two segments of code do not behave in the same way:

HOWEVER, THIS...

if ((i > 0) && (i < 10)) {
int a = 10;
a = a / 3;
System.out.println("i is between 0 and 10");
}

IS NOT THE SAME AS...

if ((i > 0) && (i < 10))
int a = 10;
a = a / 3;
System.out.println("i is between 0 and 10");

In this last example, only the first statement (assigning a the value of 10) is executed if and only if the condition checked is true. The other two statements (a is assigned one third its value and the println statement) get executed regardless of whether or not the condition checked is true. Correcting the indentation to reflect what the code actually does yields:

if ((i > 0) && (i < 10))
int a = 10;
a = a / 3;
System.out.println("i is between 0 and 10");

The effect of an extra semicolon

Be careful not to add a semicolon at the end of an if clause. This lone semicolon will be treated by Java as a "do-nothing" statement.

BE AWARE, THIS...

{
System.out.println("The area is " + area);
}

IS THE SAME AS...

{
//do nothing
}

System.out.println("The area is " + area);

The "if-else" conditional

In the case where if a condition is met, some action(s) must be taken, while if that same condition is not met, some other action(s) must be taken, the "if-else" conditional is better suited to the task.

Syntax

if (someCondition) {
statement(s);
}
else {
statement(s);
}

Example

System.out.println("Area of circle equals " + area);
}
else {
}

Nested vs. Chained "if-else" statements

A program can distinguish between several different conditions and act accordingly using "nested" if-else statements, as shown below. Unfortunately, using the standard conventions for indention, your code can slowly "drift to the right" when there are a large number of cases to be distinguished. This can be annoying, especially if you have to print your code out to read it. So, in some cases, we abandon our normal indention conventions and simply "chain" the if-else statements together as shown in the second (and equivalent) example below.

THIS...

if (score >= 90.0)
else
if (score >= 80.0)
else
if (score >= 70.0)
else
if (score >= 60.0)
else

IS THE SAME AS...

if (score >= 90.0)
else if (score >= 80.0)
else if (score >= 70.0)
else if (score >= 60.0)
else

How "if" and "else" are paired

Be careful, any given "else" will be paired with the most recent "if" in the same block. So, despite what the indentation in the first example suggests, the following two examples do the same thing.

THIS (despite the incorrect indentation)...

int i = 1;
int j = 2;
int k = 3;

if (i > j)
if (i > k)
System.out.println("A");
else
System.out.println("B");

IS EQUIVALENT TO THIS...

int i = 1;
int j = 2;
int k = 3;

if (i > j)
if (i > k)
System.out.println("A");
else
System.out.println("B");

To force the "else" to match the first "if", one must add a pair of curly braces:

int i = 1;
int j = 2;
int k = 3;

if (i > j) {
if (i > k)
System.out.println("A");
}
else
System.out.println("B");

(By the way, the code above prints a "B".)

The Conditional Operator, ?

In Java, the conditional operator, "?", is used to create an expression whose value is one thing if a given condition is true, and another if it is false.

Syntax

(booleanExpression) ? valueIfTrue : valueIfFalse

So for example, rather than using an "if-else" pair to assign a value to the variable y, we can use the conditional operator and a single assignment statement, as shown below

THIS...

if (x > 0)
y = 1;
else
y = -1;

IS THE SAME AS...

y = (x > 0) ? 1 : -1;

The conditional operator is not limited to assignment, however. It can be used anywhere we need an expression. To print whether or not a number is even, for example, we could use an "if-else" pair, or we could use a conditional operator:

THIS...

if (num % 2 == 0)
System.out.println(num + " is even");
else
System.out.println(num + " is odd");

IS THE SAME AS...

System.out.println((num % 2 == 0) ? (num + " is even") : (num + " is odd"));

The "switch" conditional

The "switch" statement in Java at first blush appears similar to an "if-else" chain. It allows you to act in several different ways depending upon the value of a given expression.

Syntax

switch (expression) {
case value1: statement(s);
break;
case value2: statement(s);
break;
...
case valueN: statement(s);
break;
default: statement(s);
}

The value of "expression" is compared sequentially to "value1", "value2", ..., "valueN". The statements corresponding to the first value matched are executed. Statements below these (the ones belonging to other cases) are also executed until a "break;" or the end of the switch statement is encountered. If none of the listed values match the expression, the statements corresponding to the "default" case are executed.

Example

switch (dayOfWeek) {
case 0: System.out.println("Sunday");
break;
case 1: System.out.println("Monday");
break;
case 2: System.out.println("Tuesday");
break;
case 3: System.out.println("Wednesday");
break;
case 4: System.out.println("Thursday");
break;
case 5: System.out.println("Friday");
break;
case 6: System.out.println("Saturday");
break;
default: System.out.println("Not a valid day");
break;
}

The "default" case

The default case provides the statements to be executed if no case's value matches the given expression. Note, no "default" case need be specified. In the case of its omission, an expression that does not match any case will simply result in nothing happening.

Example (with default case)

number = 'e';

switch (letter) {
case 'a': System.out.println("Apple");
break;
case 'b': System.out.println("Bee");
break;
case 'c': System.out.println("Cat");
break;
default: System.out.println("A word not starting with A,B, or C");
}

//This switch statement prints "A word not starting with A,B, or C".

Example (without default case)

number = 'e';

switch (letter) {
case 'a': System.out.println("Apple");
break;
case 'b': System.out.println("Bee");
break;
case 'c': System.out.println("Cat");
break;
}

//This switch statement does nothing, since the case when
//number == 'e' is not addressed, and no default is specified.

The "break" statements

Also, the "break" statements do not have to appear as shown in the examples above. Some or all may be omitted, but their omission impacts what statements get executed. If you only want the statements belonging to a single case to be executed when the examined expression equals the value corresponding to that case, you should put a "break;" after these statements.

Example

dayOfWeek = 2;

switch (dayOfWeek) {
case 0: System.out.println("Sunday");
case 1: System.out.println("Monday");
case 2: System.out.println("Tuesday");
case 3: System.out.println("Wednesday");
case 4: System.out.println("Thursday");
case 5: System.out.println("Friday");
break;
case 6: System.out.println("Saturday");
break;
default: System.out.println("Not a valid day");
break;
}

// Since a break is not encountered until case 5,
// this will print:
//   Tuesday
//   Wednesday
//   Thursday
//   Friday

Style Tips

Assigning a value to a boolean variable

boolean even;
if (number % 2 == 0)
even = true;
else
even = false;

BETTER...

boolean even = (number % 2 == 0);