Tutorials

Decision Making Statement


if-else statement


In if statement we found that code inside if block is executed only when condition is found to be true. But what to do in case condition is false.
 
This is where if-else statement comes handy.
 
First see the syntax given below,
 
Syntax of if-else
if(testCondition){
   //code to execute for true condtion
}else{
  //code to execute for false condition
}

In this case if test condition results in false then else block will get executed. Let’s learn more about it in the example given below. 
 
Example: If I reach bus stop before 9:00AM then I will take public bus else I will book Ola or Uber.
 
import java.util.Scanner;

public class UseIf {

     public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter time:");
        int time = sc.nextInt();

        if(time<=9){
        System.out.println("Take public bus as transport");
        }else{
        System.out.println("Book Ola or Uber");
       }

   }

}

Output:
Enter time:
10
Book Ola or Uber
 
This time your code knows what decision should be made in case your test condition is false. It knows if you are late to bus stop, you should "Book Ola or Uber"  
 

Drawback of if-else statement

In both if and if-else statement, we found that our decision making capability is subject to just one test condition. But real life scenarios is not just about if and else. It is like, if abc is true I will do this else if xyz is true I will do this else if pqr is true and so on.  What I mean is there could be multiple test conditions that could be checked and based on it we may make our decision.
 

Solution to the drawback

if-else-if ladder solves our problem. Let’s learn more about it in next section.
 


Please Share this page
Views : 40