• The If, Else If, Else

    In programming, you should know the basic condition statement and loops. In this chapter, we will discuss the if, else if and else statement.

    The If statement

    The construction of an if statement is like this:

    if(condition){
         //code to be executed when the 
         //condition will result to true.
    }

    The program will test if the condition is true. If the condition is true, the program will go inside the if bracket and execute whatever codes that is inside the bracket. For example,

    int num=20;
    if(num>10){
         System.out.println("Above 10");
    }

    The num variable holds a value of 20. Next, in the if statement, the condition statement will be execute and test if it will return to true. Does num is greater than 10? or does 20 is greater than 10? Of course, the answer is yes and it will return true and therfore, it will print an output of “Above 10”.

    The If, Else statement

    The construction of an if-else is this:

    if(condition){
         //codes to be executed when the
         //condition returns to true
    }else {
         //the codes to be executed when
         //the condition returns false.
    }

    It goes like this, if the condition is true, then execute this, else if its not true, then execute this instead. For example,

    int num=10;
    if(num>10){
         System.out.println("The number is greater than 10");
    }else {
         System.out.println("The number is less than or equal to 10");
    }

    The num variable will be tested and if it is greater than 10, it will output “The number is greater than 10”, but if its not, the program will automatically fall to else statement and print “The number is less than or equal to 10”.

    The If, Else If, Else statement

    The if, else if, else statement is just a series of conditions that will test a given value and will go to else statement if no conditions is true. For example,

    int num=20;
    if(num==0){
         System.out.println("The number is 0");
    }else if(num<10){
         System.out.println("The number is greater than 0 but less than 10");
    }else {
         System.out.println("The number is greater than or equal to 10");
    }

    In the above codes, the num variable will be tested for conditions. If it satisfy the condition, it will execute the code inside the bracket. Take note that only one bracket of codes can be executed. For example, if num==0 returns to true, the remaining else if and else statement will be skipped and will never be called and automatically, the program will end the conditions. Thus, it saves processing time. The else statement will only be called when all the if conditions returns false.

    Related Post