Branching Statements

Up to this point, we’ve only observed code that has one path in the flow of control.

statement 1;
statement 2;
statement 3;
….
Done

In other words, all of the instructions of the code we’ve seen up to this point are executed in a serial manner and then the program ends.

Wouldn’t it be nice to execute different instructions a set of conditions were true?

Take my phone as an example. It runs software and it behaves differently depending on what’s going on. To ensure the battery lasts all day the screen better be off until I turn it on.

That means, although my phone is on, if my phone is in my pocket the screen is off. When I pull the phone out of my pocket the screen is still off. However, if I press the screen button it turns on!

The state of my phone screen being on or off could be a boolean, couldn’t it?

boolean phoneScreenOn = false;

Also, the state of the button to turn my screen on could be a boolean, too.

boolean buttonToTurnScreenOnIsPress = false;

So, on the event that buttonToTurnScreenOnIsPressed is equal to true, phoneScreenOn needs to equal true.

Booleans and boolean expressions become a programmer’s best friend when they’re coupled with branching statements! Branching statements allow programmers to alter the control flow of code based on Booleans and Boolean statements conditions.

Here’s an example of an if statement.

if(austinsTeaching){
      System.out.println("All students better be taking notes.");
}

Consider the phone screen example, again. We can use an if statement to make sure phoneScreenOn is only set to true when buttonToTurnScreenOnIsPressed is true.

if(buttonToTurnScreenOnIsPressed){
      phoneScreenOn = true;
}