Navigate Language Fundamentals topic: v  d  e )


Conditional blocks allow a program to take a different path depending on some condition(s). These allow a program to perform a test and then take action based on the result of that test. In the code sections, the actually executed code lines will be highlighted.

The if block executes only if the boolean expression associated with it is true. The structure of an if block is as follows:

if (boolean expression1) {
statement1
statement2
...
statementn

}

Here is a double example to illustrate what happens if the condition is true and if the condition is false:

  Code section 3.22: Two if blocks.
int age = 6;
System.out.println("Hello!");

if (age < 13) {
  System.out.println("I'm a child.");
}

if (age > 20) {
  System.out.println("I'm an adult.");
}

System.out.println("Bye!");
  Output for Code section 3.22
Hello!
I'm a child
Bye!
  If only one statement is to be executed after an if block, it does not have to be enclosed in curly braces. For example, if (i == 0) i = 1; is a perfectly valid portion of Java code. This works for most control structures, such as else and while. However Oracle's Java Code Conventions explicitly state that the braces should always be used.

If/else

edit

The if block may optionally be followed by an else block which will execute if that boolean expression is false. The structure of an if block is as follows:

if (boolean expression1) {
statement1
statement2
...
statementn

} else {

statement1bis
statement2bis
...
statementnbis

}


If/else-if/else

edit

An else-if block may be used when multiple conditions need to be checked. else-if statements come after the if block, but before the else block. The structure of an if block is as follows:

if (boolean expression1) {
statement1.1
statement1.2
...
statementn

} else if (boolean expression2) {

statement2.1
statement2.2
...
statement2.n

} else {

statement3.1
statement3.2
...
statement3.n

}

Here is an example to illustrate:

  Code listing 3.3: MyConditionalProgram.java
public class MyConditionalProgram {
    public static void main (String[] args) {
      int a = 5;
      if (a > 0) {
          // a is greater than 0, so this statement will execute
          System.out.println("a is positive");
      } else if (a >= 0) {
          // a case has already executed, so this statement will NOT execute
          System.out.println("a is positive or zero");
      } else {
          // a case has already executed, so this statement will NOT execute
          System.out.println("a is negative");
      }
    }
}
  Output for code listing 3.3
a is positive

Keep in mind that only a single block will execute, and it will be the first true condition.

All the conditions are evaluated when if is reached, no matter what the result of the condition is, after the execution of the if block:

  Code section 3.23: A new value for the variable a.
int a = 5;
if (a > 0) {
    // a is greater than 0, so this statement will execute
    System.out.println("a is positive");
    a = -5;
} else if (a < 0) {
    // a WAS greater than 0, so this statement will not execute
    System.out.println("a is negative");
} else {
    // a does not equal 0, so this statement will not execute
    System.out.println("a is zero");
}
  Output for code section 3.23
a is positive

Conditional expressions

edit

Conditional expressions use the compound ?: operator. Syntax:

boolean expression1 ? expression1 : expression2

This evaluates boolean expression1, and if it is true then the conditional expression has the value of expression1; otherwise the conditional expression has the value of expression2.

Example:

  Code section 3.24: Conditional expressions.
String answer = (p < 0.05)? "reject" : "keep";

This is equivalent to the following code fragment:

  Code section 3.25: Equivalent code.
String answer;
if (p < 0.05) {
    answer = "reject";
} else {
    answer = "keep";
}

Switch

edit

The switch conditional statement is basically a shorthand version of writing many if...else statements. The switch block evaluates a char, byte, short, or int (or enum, starting in J2SE 5.0; or String, starting in J2SE 7.0), and, based on the value provided, jumps to a specific case within the switch block and executes code until the break command is encountered or the end of the block. If the switch value does not match any of the case values, execution will jump to the optional default case.

The structure of a switch statement is as follows:

switch (int1 or char1 or short1 or byte1 or enum1 or String value1) {
case case value1:
statement1.1
...
statement1.n
break;
case case value2:
statement2.1
...
statement2.n
break;
default:
statementn.1
...
statementn.n

}

Here is an example to illustrate:

  Code section 3.26: A switch block.
int i = 3;
switch(i) {
    case 1:
        // i doesn't equal 1, so this code won't execute
        System.out.println("i equals 1");
        break;
    case 2:
        // i doesn't equal 2, so this code won't execute
        System.out.println("i equals 2");
        break;
    default:
        // i has not been handled so far, so this code will execute
        System.out.println("i equals something other than 1 or 2");
}
  Output for code section 3.26
i equals something other than 1 or 2

If a case does not end with the break statement, then the next case will be checked, otherwise the execution will jump to the end of the switch statement.

Look at this example to see how it's done:

  Code section 3.27: A switch block containing a case without break.
int i = -1;
switch(i) {
    case -1:
    case 1:
        // i is -1, so it will fall through to this case and execute this code
        System.out.println("i is 1 or -1");
        break;
    case 0:
        // The break command is used before this case, so if i is 1 or -1, this will not execute
        System.out.println("i is 0");
}
  Output for code section 3.27
i is 1 or -1

Starting in J2SE 5.0, the switch statement can also be used with an enum value instead of an integer.

Though enums have not been covered yet, here is an example so you can see how it's done (note that the enum constants in the cases do not need to be qualified with the type:

  Code section 3.28: A switch block with an enum type.
Day day = Day.MONDAY; // Day is a fictional enum type containing the days of the week
switch(day) {
    case MONDAY:
        // Since day == Day.MONDAY, this statement will execute
        System.out.println("Mondays are the worst!");
        break;
    case TUESDAY:
    case WEDNESDAY:
    case THURSDAY:
        System.out.println("Weekdays are so-so.");
        break;
    case FRIDAY:
    case SATURDAY:
    case SUNDAY:
        System.out.println("Weekends are the best!");
        break;
}
  Output for code section 3.28
Mondays are the worst!

Starting in J2SE 7.0, the switch statement can also be used with an String value instead of an integer.

  Code section 3.29: A switch block with a String type.
String day = "Monday";
switch(day) {
    case "Monday":
        // Since day == "Monday", this statement will execute
        System.out.println("Mondays are the worst!");
        break;
    case "Tuesday":
    case "Wednesday":
    case "Thursday":
        System.out.println("Weekdays are so-so.");
        break;
    case "Friday":
    case "Saturday":
    case "Sunday":
        System.out.println("Weekends are the best!");
        break;
    default:
        throw new IllegalArgumentException("Invalid day of the week: " + day);
}
  Output for code section 3.29
Mondays are the worst!