JAVA LESSON 9 – IF/ELSE STATEMENTS

 


INTRODUCTION

In today's free Java lesson, we will study how our programs can make decisions based on a condition or conditions that we have defined. We will also analyze the concept of a block and how it is combined with local scope.

BLOCK STATEMENT

In Java, a statement is defined as any action that has a complete outcome, such as the declaration of a variable, the assignment of a value to a variable, the printing of a result to the terminal, etc. Also, as you already know, every statement must end with a semicolon ( ; ).

A block is a group of statements whose beginning and end are defined by braces ( { } ). Variables that are declared inside the block can only be used by code within the same block. In other words, the scope of the variable (i.e., which code has access to it) is limited to that same block. This is called local scope.

The following is the general syntax for a block of statements.

{
    statement1;
    statement2;
    statement3;
}

Let’s look at a simple example through which you will be able to fully understand the concept of local scope. For better explanation of the code, comments have been added to each line of the program. The following program cannot be executed.

App.java

package com.example;

public class App {

    public static void main(String[] args) {
        // Declare a variable num1
        // The scope of this variable is the main method
        int num1;
        // Start of a block statement
        {
            int num2; // Declare a num2 variable inside the block
            num2 = 200; // num2 is local to this block

            num1 = 100; // num1 is declared outside the block, so
                        // from inside the block we can reach it
        } // End of the block statement

        num2 = 50; // A compile-time error. num2 has been
                   //declared inside a block and
                   //so it cannot be used outside that block
                   // This program can not be compiled.

    }
}

Output



In the above example, the main point is to understand that the variable num1, which was declared at the method level, is accessible by the inner blocks we created. However, the opposite is not true. That is, the variable num2, which was declared inside its own block, is not accessible by code at the main method level.

IF STATEMENT

The usefulness—and consequently, the concept—of a block becomes clearer when it is used in combination with other logic structures such as if statements. The if statement adds the ability for our program to decide the flow of code execution based on the result of one (or more) true/false conditions.

The if statement consists of a Boolean expression followed by one or more statements. The general syntax rule of an if statement is as follows:

if(Boolean_expression){
// Statements will execute if the Boolean expression is true
}


If the Boolean expression inside the parentheses evaluates to true, then the statements within the block (defined by the braces { }) will be executed. However, if the Boolean expression is false, the statements inside the if block will not be executed—the program will skip them and continue executing the rest of the application code.

In the following example, we will use the if statement to congratulate the student if the average of the three exams is greater than 95. If it is not, then the extra message inside the if block will not be displayed.

App.java

package com.mycompany;


public class App {


public static void main(String[] args) {

int HIGH_SCORE = 95;


int test1 = 95;

int test2 = 97;

int test3 = 98;


int average = (test1 + test2 + test3) / 3;


System.out.println("The average score is " + average);


if (average >= HIGH_SCORE) {

System.out.println("Congratulations!");

System.out.println("Excellent effort on your exams");

}


}


}

Output

Based on the above example and the theory we have covered so far, you understand that when we have multiple if statements within the same program, all of those for which the Boolean expression is true will be executed. Let’s look at an example where we have such a case.

App.java

package com.mycompany;


public class App {


public static void main(String[] args) {

int x = 10;

double half = 0.0;


if (x != 0) {

half = x / 2.0;

System.out.println(x + "/2 = " + half);

}


if (x == 0) {

System.out.println("The value of x is 0");

}


int y = x * 5;

char grade = 'F';


if (y >= 85) {

grade = 'A';

}


if (y >= 70 && y < 85) {

grade = 'C';

}

if(x>=0 && y>=0) {

System.out.println("This is too general");

System.out.println("Please specify the exact values");

}


System.out.println("y = " + y + " and grade = " + grade);

}


}

Output

In the above code, we observe that we can use Relational Operators to perform the various comparisons we need.

Note the double equal sign (==) represents a comparison and not an assignment of value. The table below summarizes all the Relational Operators.


There are also Boolean Operators: AND (&&), OR (||), and NOT (!).

 


IF ELSE STATEMENT

The above functionality of the if statement, although desirable, is not absolutely perfect. Usually, we want to have a series of if statements, and only one should be executed (the one that first satisfies the condition), with the rest being ignored. We can achieve this by adding an else after the if.

App.java

package com.mycompany;


public class App {


public static void main(String[] args) {

int score = 79;

char grade;


if (score >= 90) {

grade = 'A';

System.out.println("Way to go!");

} else if (score >= 80) {

grade = 'B';

System.out.println("Good job!");

} else if (score >= 70 && score < 80) {

grade = 'C';

} else if (score >= 60) {

grade = 'D';

} else {

grade = 'F';

System.out.println("Try again");

}


System.out.println("Your grade is a " + grade);

}


}

Output

In this simple code from the above example, we assign the value 79 to an int variable named score. The value of the variable is checked by a series of if-else statements. The condition (score >= 70 && score < 80) is satisfied and returns true. I remind you that for the AND to return true, both of its terms must be true.

Also, at the end of the code, there is an else by itself. This is the way we check for any other condition that we haven't written an if statement for. This way, we have full control over our program, because essentially, either a value will belong to one of the if statements or not, and it will be covered by the final else.

Don't forget to make a small donation so that this blog can grow even more and have more capabilities for delivering free lessons online.


full-width

Post a Comment

0 Comments