Tutorials

Java Decision Making Statement


Java if statement


Many a time in life, we come across a situation where we have to test certain conditions and then depending on the result obtained we have to make our decision. 
 
For Example, if I reach bus stop at 9:00 AM then I will take public bus as transport or else I will book an Ola cab for myself.
 
In similar way, the programming languages like C, Java, etc makes use of if statements to test certain conditions and make decisions.
 
Various type of decision making statement that we make use of in java is:
  • if statement
  • if-else statement
  • if-else-if statement
  • Nested if statement
  • Switch statement

Let's learn each of them one by one.

 

if statement in java

In java, if statement test the condition first and executes if block only when the condition is found to be true. 
 
Syntax
if(testCondition){
   //code to execute
}

 
Example: If I reach bus stop before 9:00AM then I will take public bus.
 
import java.util.Scanner;

public class UseIf {

     public static void main(String[] args) {
       Scanner sc = new Scanner(System.in);  //recieves input from user on console
       System.out.println("Enter time:");
       int time = sc.nextInt();

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

   }

}

OUTPUT:
Enter time:
8
Take public bus as transport
 
Note: For the reason of simplicity we are measuring time as int value in this example. Once we learn about handling Date & Time in java we can code using real time.
 
Suppose I reached at 8 AM. Condition within if is tested and since 8<9 (is true) so the code within if block gets executed and we got the decision "Take public bus as transport" as output.
 

Drawback of if statement

In ‘if statement’ the body within if block gets executed when testing condition results in true.
 
But what decision should be made when condition is false?
To understand this fact execute the above code once again and enter any time greater than 9(int value only). You will find nothing is printed as output. It means that your code doesn’t know what should be done in negative (false) scenario. 
 

Solution to the drawback

if-else statement solves the above problem. Let’s learn more about it in next section.


Please Share this page
Views : 160
Like every other website we use cookies. By using our site you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our Terms of Service. Learn more Got it!