Java Keywords (Part VI): If/Else Flow-Control Statements


The Java keyword list has 19 keywords grayed out. That puts us at 38% of keywords covered by these series of articles. Amazingly, that's almost sufficient to built simple applications. I suggest that if have not read any of the articles in Java Keyword series, you read them before proceeding further. Also, go back and read the one about Data Types. All of these articles are from September 2018. That should help you find them quickly. This article will only cover the if and else keywords.

Java keyword list

abstract continue for new switch
assert default goto* package synchronized
boolean do if private this
break double implements protected throw
byte else import public throws
case enum instanceof return transient
catch extends int short try
char final interface static void
class finally long strictfp volatile
const* float native super while
Keyword marked with an asterisk (*) are keywords that, although valid, are not used by programmers.

Although the list above is arranged in alphabetical order, I will go through them in a different order.

What is a flow control statement?

Simply put, a flow control statement is a piece of code that has the ability to alter the execution path of a program. For example, think of your typical chime in a home alarm system. When you open a door or a window, a sound alerts you that a door or window has been opened. Or, think of your typical refrigerator works. When the temperature inside the refrigerator rises above a preset threshold, the compressor motor kicks in and the refrigerator starts cooling. Then, when the temperature inside the refrigerator falls under a preset threshold, the motor stops. With that in mind, it should be obvious to you that complex programs need the ability to make decisions based on the evaluation of certain conditions. Depending on the outcome of these evaluations, the program will decide which execution path must be followed. One of such flow-control are the If-Else structure. Let start with the if-statement.

if-statement


if(boolean-expression) {
  // Execute whatever is inside this block only 
  // when "boolean-expression" evaluates to true
}
The purpose of the if-statement is to allow access to some code ONLY when the evaluated expression is true. Otherwise, the enclosed code will be skipped. Using the previous example of the alarm system chime, you could have some code that might look something like this:


boolean open = alarm.isDoorOpen(); // method that returns "true" if the door is open

if(open) {
  alarm.playChime(); // plays chime sound for one second
}
In the above code snippet, if the door is closed (Boolean variable "open" has a value of false), the alarm chime will not go off. As you can see, the flow of execution in the code changes depending of the result of the evaluation. Sometimes it will execute the code inside the if-statement and sometimes it will skip over it.

You can do more complex evaluations. Suppose you write an application to help users learn math. Your application presents random math problems to the user and the user must respond with the correct answer. Let us assume that the program has presented the user with a simple addition problem; 3 + 2. The user enters the result. Your code will take the user input and calls a function to determine whether the answer enter is correct.



public void evaluateSum(double a, double b, double answer) {

    if(a + b == answer) {
        System.out.println("Your answer is correct!");
    }
}
In the above example, the Boolean expression being evaluated is the result of the equality comparison between the sum of the two numbers presented to the user and the result provided by the user. IF the two values are the same, a message will be send shown on the screen. But Boolean expressions are much more than checking for equality. Inequalities also evaluate to true or false. For instance, 4 + 3 > 1 evaluates to true because the sum of 4 plus 3 is greater than one. Such expressions can be used with an if-statement.

else-statement

The else-statement supplements an else-statement. The previous example shown for evaluating the result of a sum is really a poor example because it only shows one message ("Your answer is correct"). What if the answer is wrong? There is no message displayed which can be very confusing. A better solution will be to supplement an if with an else such as the following:


public void evaluateSum(double a, double b, double answer) {

    if(a + b == answer) {
        System.out.println("Your answer is correct!");
    } else {
        System.out.println("Your answer is incorrect!");
    }
}

Nested if-else statements

If-statements can only have a supplemental else-statement. However, if-statements can be nested in other if-statements to provide multiple decision points. Suppose you need to provide a function that evaluates a student's grade point to display the letter grade. You might do something like this:


public void evaluateGrade(double points) {

    if(points >= 90.0) {
        System.out.println("Your grade is A");
    } else {
        if (points >= 80.0) {
            System.out.println("Your grade is B");
        } else {
            if (points >= 70.0) {
                System.out.println("Your grade is C");
            } else {
                if (points >= 60.0) {
                    System.out.println("Your grade is D");
                } else {
                    System.out.println("Your grade is F");
                }
            }
        }
    }
}
The above code looks messy, but it works. Each if-statement has an accompanying else. Starting from the top, if a grade point is 90.0 or higher, the grade is an "A." Otherwise, the grade is something else other than an "A." Therefore, inside this else we must evaluate what this "non-A" letter grade is. To that end, we nest another set of if-else statements to determine the correct letter grade. The result is a nested if-else which is a few layers deep. In the last layer, we have already eliminated grade points that are greater or equal to 70.0. What is left is whether the letter grade is a "D" or an "F." The resulting if-else statement reflects this point.

Alternatively, the above nested if-else can be written as follows to be more readable:



public void evaluateGrade(double points) {

    if(points >= 90.0) {
        System.out.println("Your grade is A");
    } else if (points >= 80.0) {
        System.out.println("Your grade is B");
    } else if (points >= 70.0) {
        System.out.println("Your grade is C");
    } else if (points >= 60.0) {
        System.out.println("Your grade is D");
    } else {
        System.out.println("Your grade is F");
    }
}
As you can see, this nested if-else structure is much easier to read that its predecessor. To convert the first version to this version, I removed the opening curly braces in between the else and if, and then I removed the same number of closing curly braces. In this example, they were three pairs of curly braces removed.

Comments

  1. Control statements are used to control flow of execution of program based on certain conditions. In flowchart, boolean expression is placed in a rhombus. A branch coming from 1 corner leads to statements if boolean expression evaluates to true, otherwise else statements will be executed. However, if we use if else chaining or nested if, it can be looked more complex. To avoid that, we can use codes in small blocks.

    ReplyDelete
  2. java keywords(part vi) : this blog explain about if/else flow controlled statement and its importance in programing. this blog also explains how controlled statements can help you to get your coding to desired path.

    ReplyDelete

Post a Comment

Popular posts from this blog

Combining State and Singleton Patterns to Create a State-Machine

Exception Handling: File CRUD Operations Example

The Beauty of the Null Object Pattern