If statements and switch statements

If Statements

The if statement is a fundamental programming construct. An If statement allows a program to execute different blocks of code depending on the result of a test condition. This is an example of a basic If statement in Java:

if(condition == true){
      //do something
}
else{
     //do something else
}

Where condition is a boolean which can be either true or false. If the condition boolean holds a value of true then the Java code represented by the comment "do something" is executed. Otherwise, the code represented by the comment “do something else” is executed. The else statement is optional, so the simplest example of the if statement is:

if (age == 1){
        System.out.println("Its a baby!");
}

A block of code is either a single line of code or several lines of code contained in curly braces. Note that in this example, enclosing the code in curly braces is not required, although some programmers prefer to use them anyway since it makes it clearer what code is exectued.

Multiple else if conditions can be chained together:

if ( x == 1 )

System.out.println("One");

else if ( x > 1 ) {

y = x*2;
System.out.println("Many");

} 

else {

y = -x;
System.out.println("Negative");

}

Switch Statements

Switch statements are shorthands for a certain kind of if statement. It is not uncommon to see a stack of if statements all relate to the same variable like this:

if (x == 0) {

doSomething0();

}
else if (x == 1) {

doSomething1();

}
else if (x == 2) {

doSomething2();

}
else if (x == 3) {

doSomething3();

}
else if (x == 4) {

doSomething4();

}
else {

doSomethingElse();

}

Java has a shorthand for these types of multiple if statements, the switch statement. Here's how you'd write the above using a switch statement:

switch (x) {
  case 0: 
    doSomething0();
    break;
  case 1: 
    doSomething1();
    break;
  case 2: 
    doSomething2();
    break;
  case 3: 
    doSomething3();
    break;
  case 4: 
    doSomething4();
    break;
  default: 
    doSomethingElse();
}

The variable "x" must be an int, byte, short or char. "x" is compared with the value of each the case statements in succession until one matches. This example compares x to exact values, but these too could be variables or expressions as long as the variable or result of the expression is an int, byte, short or char. If no cases are matched, the default action is triggered.

Once a match is found, all subsequent statements are executed until the end of the switch block is reached or you break out of the block. This can trigger decidedly unexpected behavior. Therefore it is common to include the break statement at the end of each case block. It's good programming practice to put a break after each one unless you explicitly want all subsequent statements to be executed.

Video Tutorial (IF Statements)

Video Tutoral (Switch Statments)