Conditionals: PDF version

There are three types of conditionals in java. If statements, switch statements and ternary statements, we will discuss the details in the following sections. If statements: The syntax for if statements is as follows:


            if ( <Some expression that would evaluate to a true/false>) {
            // the body of your if statements.
            } else if( < more boolean expression> ){
            // the body of your else if
            // you can have multiple else if statements if you have multiple conditions
            } else {
            // body of else, notice there are no conditions in this case.
            // this part will only execute if none of the conditions are met in the above if and else if statements.
            }
        

If the body of the if statement consist of only one statement, then the curly braces are optional. For example:

            if (num > 0){
            System.out.println(“positive number”);
            }
            

Is equivalent to

            if (num > 0)
                System.out.println(“positive number”);
            

or

            if (num > 0)
            System.out.println(“positive number”);
            

Again, remember that indentation does not matter at all in java and if there are no curly braces in if statements, only the immediate following statement will be considered the body of the if statements. Short circuiting The idea behind this is Java will do the minimum work possible while evaluating boolean expression. Let’s consider this scenario: A|| B If A evaluates to true, then it doesn’t matter what B is anymore, because true || false, true || true both result to true, we can tell what this expression is true if we know that A is true. We don’t care what B is, the truth is, java doesn’t give a sheet about it either. B will NOT be evaluated if A is true. To prove that, consider having the following code

            if ( 1 < 3 || 1 / 0 == 5) {
            System.out.println(“we passed the test”);
            }
            

Recall that 1/0 would result into a runtime error, because you can’t divide by 0. However, because 1 < 3 is true, so 1 / 0 doesn’t get evaluated and hence does not error out. If we change the code into this

            if ( 1 > 3 || 1 / 0 == 5) {
            System.out.println(“we passed the test”);
            }
            

Since the 1 > 3 is false, java couldn’t determine the outcome of this expression without knowing the second part of the boolean expression and is forced to evaluate the 1 / 0 and would error out. There are two possible ways for short circuit to happen, the first is what we have been describing, you encounter || operator while the first part is true, the other one is when you encounter && operator while the first part is false. For && operators, if the first expression evaluates to false, the entire statement will be false regardless of what the second expression evaluates to. Ternary Statements: Ternary statements are used when you want to assign a value based on a boolean expression. In English, we would use ternary when we encounter a situation like “ I want to assign a certain value to this variable IF under some conditions”. The syntax is kind of weird, so here it is: < some variables > = < boolean expression> ? <value if the expression is true> : <value if expression if false> ; For example

                int grade = 69;
                String msg = (grade >= 95) ? “You passed” : “You Failed”;
            

You can only use ternary for assignments, for example:

                (a > 3)? System.out.println(“a > 3”): System.out.println(“a <= 3”);
            

Honestly, ternary isn’t very common, but it can come in handy and save you a couple lines of code if the time is right. Switch statements: Switch statements are the third part of the control flow logic. Now that we have learned about if statements, switch statements can be seen as a bunch of if, else if statements. The syntax is as follows

                switch(< variable >){

                    case < possibility of what the variable is > :
                        //body of this specific case
                        break;
                        case < possibility of what the variable is> :
                            // body of this specific case
                            break;

                            default:
                            // this is just like the else clause in if statements, if none of the case were //passed into then this will execute.
                            break;
                            }

                            Let’s do an example of switch statements:
                            String name = “ … “// some arbitrary string
                            switch (name){
                            case “Maddy”:
                            System.out.println(“Awesome”);
                            break;
                            case “Chase”:
                            System.out.println(“Cool”);
                            break;
                            case “Tony”:
                            System.out.println(“Meh”);
                            break;
                            default:
                            System.out.println(“Good”);
                            break;
                            }
                

Break is a keyword that you should only use for switch statements, it tells java to jump out of this block of code that is enclose by curly braces. One should avoid using break aside from switch statements because that’s considered bad coding style. In switch statements, the order does not matter for different cases if all of them have break, however, there are some restrictions: 1. You can only switch on int, String, Enum(we will talk more about this in the future). 2. You can only specify an exact data on case conditions. What that means is you cannot make a condition with a range, case num > 100 is not allowed in switch statements. 3. Although break statements are optional, it would introduce weird behavior of your code. What happens if you missed the break statements? Your code will “fall through” to other cases below and continue executing until you hit a break somewhere or reached the end of the switch block. Consider the same problem but without the break.

                            String name = “ … “// some arbitrary string
                            switch (name){
                            case “Maddy”:
                            System.out.println(“Awesome”);
                            case “Chase”:
                            System.out.println(“Cool”);
                            case “Tony”:
                            System.out.println(“Meh”);
                            default:
                            System.out.println(“Good”);
                            }
                

If name was assigned “Maddy, and then start executing switch, java sees that it has a match in the first case, and prints out Awesome, then continues executing the program since there are no break to stop it. Hence, it falls through case “Chase”, case “Tony” and default and execute all of them. This program will output Awesome Cool Meh Good That is usually not what we want the program to behave. If the name was assigned the value “Chase”, it’ll print out Cool Meh Good Since the code only start falling through from the second case. Order matters if we are missing the break clause. I encourage you play around with different combination of switch statements and break to see what happens. If you see on the exam that you have to trace switch statement then first make sure if break exist or not. Most likely, there isn’t break.