Branching

Dr Andy Evans

[Fullscreen]

Branching

  • Processing can rarely be done by a single list of instructions.
  • We usually need to have different sets of code running, depending on conditions or user interaction.
  • For this, we need to branch our code down one or more execution paths.

If

  • The simplest form is the if-statement:
    if (some condition) { 
        do something; 
    }
    
  • For example:
    if (earthRadius == 6378) {	
        System.out.print("radius correct");
    }
    
  • Block only done if the whole condition is true.
  • Note that if there's only one line, it can be written without brackets, but avoid this.

if... else...

  • The if-else statement lets us branch down two mutually exclusive routes:
  • if (condition) {do something;} 
    else {do something else;}
    
  • For example:
    if (earthRadius == 6378) {	
        System.out.println("radius correct");
    } else {
        earthRadius = 6378;
        System.out.println("radius corrected");
    }
    

Switch

switch (variable) {
    case value1:
		statements1;
		break;
    case value2:
		statements2;
		break;
    case value3:
		statements3;
		break;
    default:
		statements4;
}
  • Slightly slower, but not as slow as a bad if-else-if ladder.
  • The break's are optional, if you leave one out, the computer will just run on into the next values case statements.
int day = 7;

switch (day) {
    case 6:
		System.out.println("Saturday");
		break;
    case 7: 
		System.out.println("Sunday");
		break;
    default: 
		System.out.println("Meh, whatever");
}
Note that unlike the 'if / else if / else' ladder the conditions generally have to be fixed; they can't be variables (this changed with Java 7, but many people have JRE 6).

Review

if (some condition) { 
    do something; 
} else {
    do something else; 
}