Skip to content

Branching

Estimated time to read: 5 minutes

IF statements

The if statement works with the relational operators to execute a block of code only if some condition is true.

if ( x < y) {
 System.out.println("X is less than Y.");
 z - y - x;
}

When more than a single statement is required, a compound statement is required, as above (x <y )

Above, if x is less than y and the boolean is true, the code block is executed.

A message is printed to the console.

An assignment is made, z - y - x

Single statement code

If you only want to execute one statement when the if condition is true, you do not need to use braces (however, it is best practise to always include them).

For example, you could do the following, although not best practise:

int x = 7;
int y = 9;

if (x < y)
 System.out.println("X is less than Y.");
System.out.println("This line always prints");

Only the statement directly after the comparison will run, if the comparison returns true, in this instance regardless of indentation, the line is System.out.println("X is less than Y.");

Multi statement code blocks

Braces group things into a single statement:

int x = 7;
int y = 9;

if (x < y) {
 System.out.println("X is less than Y.");
 System.out.prinln("This will print if the above line printed")
}

System.out.println("This line always prints as it is not part of the comparison code block");

ELSE Statements

IF ELSE statements

Single line if else statements

You can set up a block of code that will execute only when the comparison is false

if ( availableCase > salePrice)
 System.out.println("Lemme at it!");

else
 System.out.println("Save more money :(");

Lemme at it! only prints if the condition is true Save more money :( only prints if the condition is false

Like the if code block, the else code block can be a set of statements inside braces or a single statement, as above. (This is really bad practise and I want to fix it so badly!)

The above also has an off by one error. This comparison should be an greater than, equals to

Multi-line IF ELSE statements

if (x < 7) {
 System.out.println("X is less than 7.");
 y = x - 5;
 z = y + x;
}
else {
 System.out.println("X is NOT less than 7.");
 y = x + 5;
 z = y - x;
}

The above is an example of a multi-line if else statement. Notice the use of braces and indentation to make the code more legible to a human.

Nested IF's

If statements can be nested within an if or else code block, however, the source code becomes more difficult to read although indentation helps with readability.

Nested IF example

int x = 7; 
int y = 9; 
int z = 0;

if (x > 3 ) {
 System.out.println("X>  3");
 if (y < 10) {
  System.out.println("Y < 10");
   z = x + y;
 }
x--;
}

The above example:

  • If x is greater than three, print out "X > 3".
  • If x is greater than three, then, after printing the above, check if y is less than 10.
  • If y is less than 10, assign the value of x+y to z
  • Regardless of the value of y, the last statement removes 1 from x.

Multiple IF's

An else can also include an if

int x = 7; 
int y = 9;

if (x < 3){
 System.out.println("X < 3.") ;
}
else if (x < 6) {
 System.out.println("X < 6, but not < 3.");
}
else {
 System.out.println("X > 5.");
}

If less than 3, print out X < 3. Else If less than 6, print out X < 6, but not < 3. If it matches neither, print out X > 5.

Ternary Expressions

Ternary expressions produce a value based on the truth of an expression.

There is a condition in front of the question mark;

  • If true, whatever expression is between the question mark and the colon is evaluated
  • The result of evaluating that expression is the result of the overall expression

  • If false, whatever expression comes after the colon is evaluated

  • The result of this expression is used as the result of the overall expression.

Ternary Expression example

Below is an example of a ternary expression. This example shows a conditional assignment to the variable y. By their nature, ternaries short circuit.

int y = ( x > 7) ? 2 : 5;

This is not an if statement - it is an expression that evaluates to a value.

Ternary Expression example breakdown

This expression can be broken down as such:

primitive = condition ? true value : false value ;
int y = (x > 7 ) ? 2 : 5 ;

Output

If x is greater than 7, y will be set to 2, else y will be set to 5

Ternary expressions over IFs statements

This could also be done within an IF statement, such as below:

if (x > 7){
 y = 2
}
else {
 y = 5
}

However, this is more code, more verbose and less clear to the user. It is less clear that the purpose is to do an assignment to y.

Switch Statements

A switch is not based on a condition. It is based on a comparison of values. It can be used as an alternative to a complex nested if statements.

The general syntax for a switch statement is:

switch (<integral expression>)
{
 case value1:
  <statement>;
 case value2:
  <statement>;  
 case valuen:
  <statement>;   
 default:
   <statement>;
}

The 'values' come from the evaluated expression at the start of syntax, this can be a number or a string. Switch statements allow the application to jump to the relevant case for the result.

Switch Statement example

switch (wattage) {
 case 40:
  price = 1.20;
  break; // break; statements can be used to terminates the switch
 case 60:
  price = 1.30;
  break;
 case 100: // Note that 100 has no code, it 'falls-through' to the value below it, in this case, 150.
 case 150:
  price = 1.15;
  break;
 default: // Optional catch-all
  price = 0;
}

Cases are evaluated / matched working down the top of the statement to the bottom.

Switch Statements with String evaluation

Starting from Java 7, a String value can be used within the expression.

public String getTypeOfDayWithSwitchStatement (String dayOfWeekArg){
 String typeOfDay;
 switch (dayOfWeekArg){
  case "Monday":
   typeOfDay = "Start of work week";
   break;
  case "Tuesday":
  case "Wednesday":
  case "Thursday":
   typeOfDay = "Mid Week";
    break:
  case "Friday":
   typeOfDay = "End of work week";
    break;
  case "Saturday":
  case "Sunday":
   typeOfDay = "Weekend";
   break;
  default:
   throw new IllegalArgumentException("Invalid day of the week: " + dayOfWeekArg);
 }
}