Monday, January 20, 2014

# 9 - Java Conditional Statements

Hello ,

In any programming language, decision making plays a vital role. In Java, decision making is possible with the help of conditional statements. Following are the 3 conditional statements supported by Java,
  1.        If-then
  2.        If-then-else
  3.        switch
The conditional statements are self explanatory. Let us see the syntax's and examples of each conditional statement for better understanding.

If-then

Syntax –
if(expression){
// your code goes here
}
If the expression returns true, then the code inside the if block will be executed or else it will be skipped.
Example –
public static void main(String[] args){
 int myAge;
            
 // scanner is a utility used for reading the input entered by user 
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter your age : ");
        myAge = sc.nextInt();
        
 // condition for checking if the age is greater than 18 
        if(myAge > 18){
         // if the age is 18, then the control enters the block and execute the below statement 
                System.out.println("You are eligible for voting..! ");

            }
      }

Output:
Enter your age : 44
You are eligible for voting..!
If the user enters the age less than 18, then nothing happens because we didn't tell the compiler to do anything if the age is less than 18.

Note - If the if block contains only one statement, then the curly braces are optional. See this,
// if the age is 18, then the control enters the block and execute the below statement 
 if(myAge > 18)
  System.out.println("You are eligible for voting..! ");
This works perfectly fine..! But if you have more than one statement inside the if block, then you HAVE to use curly braces or else you will get a compilation error.

If-then-else

Syntax –
if(Expression){
 // put your code that need to be executed if the expression returns true
}else{
 // put your code that need to be executed if the expression returns false
}
Example –
public static void main(String[] args){
 int myAge;           
 
 // scanner is a utility used for reading the input enterd by user 
        Scannersc = new Scanner(System.in);
        System.out.print("Enter your age : ");
        myAge = sc.nextInt();
        
 // if the age is 18, then the control enters the if block or else enters the else block 
        if(myAge > 18)
            System.out.println("You are eligible for voting..! ");
        else
            System.out.println("Sorry. You are not eligible for voting.");
      }

Output 1:
Enter your age : 12
Sorry. You are not eligible for
voting.

Output 2:
Enter your age : 55
You are eligible for voting..!
If you observe the above example, I haven’t used curly braces either for if block or for else because they contain only one statement.
In the above example, the if-else condition can be replaced by Ternary operator which produces the same output. You can learn more about Java Operators here.

See the below example.
public static void main(String[] args){
 int myAge;
 
 // scanner is a utility used for reading the input entered by user 
 Scanner sc = new Scanner(System.in);
        System.out.print("Enter your age : ");
        myAge = sc.nextInt();
            
 // Ternary Operator
 String result = (myAge > 18) ? "You are eligible for voting..! " : "Sorry. You are not eligible for voting.";
            System.out.println(result);
      }
We can also have multiple if-else conditions. Please see the below example,
public static void main(String[] args){
 int myAge;

        // scanner is a utility used for reading the input entered by user 
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter your age : ");
        myAge = sc.nextInt();

        // if the age is 18, then the control enters the if block or else enters the else block 
        if(myAge >= 60)
             System.out.println("Your age is above 60");
        else if(myAge >= 40)
             System.out.println("Your age is above 40");
         else if(myAge >= 30)
              System.out.println("Your age is above 30");
         else if(myAge >= 20)
               System.out.println("Your age is above 20");
         else
               System.out.println("Your age is below 20");
      }

Output 1: 
Enter your age : 20
Your age is above 20

Output 2:
Enter your age : 77
Your age is above 60
From the above example, you see that you can use else if keyword if you need to use multiple if-then-else conditions. Notice that, we have only one if block and one else block at any time but we can have multiple else-if blocks.

switch

A switch works with the byte, short, char and int primitive data types. It also works with Enumerated Types (you will learn about it in future posts). From Java 1.7 switch case also works with Strings..! :D
See the below example for better understanding of switch case,
public static void main(String[] args){
 int monthNum;

 // scanner is a utility used for reading the input entered by user 
        Scanner sc = new Scanner(System.in);
 System.out.print("Enter the month number: ");
 monthNum = sc.nextInt();

 switch(monthNum){
 
 case 1:
         System.out.println("This is January.!");
         break;
 case 2:
         System.out.println("This is February.!");
         break;
 case 3:
          System.out.println("This is March.!");
          break;
 case 4:
          System.out.println("This is April.!");
          break;
 default :
          System.out.println("I do not know the month..");
          }

Output 1:
Enter the month number: 4
This is April.!

Output 2:
Enter the month number: 5
I do not know the month..
If you observe the above program, the value entered by user should be matched by case number to execute the statements inside a particular case.
default is the keyword to use in switch case when the input for switch doesn't match to any case.
For every case, we have used break keyword to stop the compiler from executing the next immediate case. The break keyword is a branching statement and we gonna learn more about in my next post..! :D
See the below switch case to know what happens if we missed out using the break statement.
switch(monthNum){

case 1:
        System.out.println("This is January.!");
         break;
case 2:
        System.out.println("This is February.!");
 // break statement missed
case 3: 
        System.out.println("This is March.!");
        break;
case 4: 
        System.out.println("This is April.!");
        break;
default :
         System.out.println("I do not know the month..");
        }

Output:
Enter the month number: 2
This is February.!
This is March.!
See when the control enters the case 2, it executed the statements and moved to case 3 statements to execute as it doesn’t find a break statement.

The compiler keeps on executing the statements until it finds a break statement.


Hit Ponits:

  1. If the if block or else block contains a single statements then the curly braces are optional.
  2. In many cases, the if else condition can be replaced by Ternary Operator 
  3. If we have multiple if conditions, we have to use else if keyword.
  4. In a if-then-else conditional statements, we can have only one if block and one else block but we can have multiple else if blocks.
  5. break statement should be used in switch cases. If it is missed, then the control will also execute the next immediate cases until the control finds a break statement.
  6. break statement is a branching statement which is helpful to break the control flow in a particular situation.
Happy Learning.. Thanks..! :)


0 comments:

Post a Comment