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");
    }
    
    

Ternary kung fu

  • The ?: Ternary operator
    • A replacement for the if / else statement in assignment.
    • The most nifty move you can pull. Use it and other coders will give you a knowing nod in the street. You will be the Jackie Chan Kung Fu King/Queen of Code.
  • How do I pull this amazing move?
    	
    variable = condition?expression1:expression2;
    
    
    If the condition is true, expression1 is used, otherwise expression2 is used.

Ternary example

	
name = (fileFound==true)?(filename):(defaultName);

...is the same as...
	
if (fileFound==true) {
    name = filename;
} else {
    name = defaultName;
}

  • Why use it?
    Because we can... just because we can.

if / else / if ladder

For more complex statements with multiple choices.
	
if (condition) 
    statement or {statements;}
else if (condition) 
    statement or {statements;}
else if (condition) 
    statement or {statements;}
else
    statement or {statements;} 
	

You need to put the elements with the most chance of being true at the top, otherwise it is very inefficient.

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; 
}