Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Java Control Statement: Working with if-then-else

In this article we are going to learn about various kind of control statement used in Java.

There are mainly three kinds of control statement uses in Java.

  1. Selection Statement (or we can say conditional Statement)
  2. Repetition Statements
  3. Branching Statements

Selection Statement (conditional statement)

There Are Manly Two Kind of Conditional Statement in Java

  • If conditional statement.
  • Switch case conditional statement.

if Conditional Statement

Different form of if conditional statement is:

  • If (simple)
  • If-else (simple with else part)
  • If-else-if–else-if
  • Nested if

if (simple)

This ‘if ’ is used for only one condition if it is true then it executes the true part of if otherwise do nothing and execute the next statement of code in the programme.

Syntax

  if ( expression/condition )
   Statement;

OR

 if( expression/condition )
    {
         Statement 1;
          Statement 2;
          ...
           ...
           Statement n;
  }

Here, in above syntax if is keyword that is used in java. And expression is the any valid expression that is Boolean or return a boolean value.i.e 1==2 , true, 1==1 && true etc.

Listing 1: TestControlStatement.java

              public class TestControlStatement 
  {
                          public TestControlStatement() 
                          {
                          }
   
                           public static void main(String[] args)
                          {
                                     boolean flag=true;
  System.out.println("This a Demo of Simple If\n\n");
                                      
  if(flag)
                                                 System.out.println("True part of if");
              
                                      flag=false;
                                      if(flag)
                                      {
                                                 System.out.println("True part");
                                                 System.out.println("True part with multiple Statement");
                                      }
                          
                                      System.out.println("\n\nAfter The Excute the Next Statement");
      }
  }
  

Output Listing 1: TestControlStatement.java

This a Demo of Simple If

True part of if

After The Excute the Next Statement

Here, In above example we saw that if with one statement and if with multiple statements. in first if expression is true so it prints the true inner part of if. In the second if expression is false that’s why it does not print the true part of the if and it skips the inner part and executes the next statement of the programme.

If-else ( if with else part)

If-else is used when we require condition like either this otherwise that. In this statement if condition or expression is true then it executes the true part of if, otherwise it executes the else part or we can say that the false part of the if.

Syntax

 if ( expression/condition)
                          Statement;
  else
                          Statement;

Here,if-else with single statement .it use when we need to execute only one statement.

OR

            if( expression/condition )
              {
                          Statement 1;
                          Statement 2;
                          ...
                          ...
                          Statement n;    
  }          
  else
  {
                          Statement 1;
                          Statement 2;
                          ...
                          ...
                          Statement n;
  }

Here, if-else with multiple statement.it is use when we required executing multiple statements.

Listing 2: TestControlStatement.java

   
  public class TestControlStatement 
  {
      public TestControlStatement() 
      {
      }
   
      public static void main(String[] args)
      {
              System.out.println("This is the demo of if-else \n\n " );
                         // Here if with single statement.
                         boolean  flag=true;
                         if(flag==true)
                                     flag=false;
                         else
                                     flag=true;
                         // Here if with multiple statement.
              
                         if(flag==true)
                         {
                                     System.out.println("True Part");
                                     System.out.println("This is if-else Statement");
                                     flag=false;
                         }
                         else
                         {          
                                     System.out.println("False part");
                                     System.out.println("This is if-else Statement");
                                     flag=true;
                         }          
                                     
                         System.out.println("\n\nExcute the Next Statement");
      }
  }
  

Output Listing 2: TestControlStatement.java

This is the demo of if-else

False part

This is if-else Statement

Execute the Next Statement

Here in above example we see that if condition is true than it executes the true part of the if otherwise it execute the false part of the if.

If-else-if–else-if

In this control statement we use if with the else part. In this condition if first condition is false then it checks the next condition if it false then it checks next condition and so on.

Syntax

              If(expression/condition)
                          Statement;
              else if(expression/condition)
                          statement;
              ...
              ...
              else if(expresion/condition)
                          statement;
              else 
                          statement;

OR

If(expression/condition)
  {
                          Statement 1;
                          Statement 2;
                          ...
                          Statement n;
  }
              else if(expression/condition)
  {
                          Statement 1;
                          Statement 2;
                          ...
                          Statement n;
  }
              ...
              ...
              else if(expression/condition)
  {
                          Statement 1;
                          Statement 2;
                          ...
                          Statement n;
  }
              else 
              {
   Statement 1;
                          Statement 2;
                          ...
                          Statement n;
  }

Here in this control statement it checks first condition if true then executes the true part and skip the all else part if false then it checks next else if part and so on.

Listing 3: TestControlStatement.java

   
  public class TestControlStatement 
  {
              boolean  isNameAvailable;
              boolean  isContactNoAvailable;
              boolean  isEmailAvailable;
   
              public TestControlStatement() 
              {
                          isNameAvailable=false;
                          isContactNoAvailable=false;
                          isEmailAvailable=false;
              }
   
   
               public void checkAvailibilty()
              {
                          if(isNameAvailable)
                                      {
                                                  System.out.println("Fisrt if ");
                                                  System.out.println("Name is Available of Customer ");
                                      }
                                      else if(isContactNoAvailable)
                                      {
                                                  System.out.println("else if 2nd if");
                                                  System.out.println("Contact No is Available of Customer");
                                      }
                                      else if(isEmailAvailable)
                                      {
                                                  System.out.println("else if 3rd if");
                                                  System.out.println("Email Address is Available of Customer");                    
                                      }
                                      else
                                      {
                                                  System.out.println("Excute When All Condition is false");
                                                  System.out.println("No information is available of customer");
                                      }          
              
                                      System.out.println("\n\nExcute the Next Statement");
              
                          }
                          public static void main(String[] args)
                          {
                                      System.out.println("This the Demo of if-else-if\n\n");
                          
                                      TestControlStatement testControlStatement=new TestControlStatement();
                                      testControlStatement.isEmailAvailable=true;
                          
                                      testControlStatement.checkAvailibilty();
                          }
  }
  

Output Listing 3: TestControlStatement.java

This the Demo of if-else-if

else if 3rd if

The customer’s email address is available

Execute the Next Statement

Nested if

This 'if' statement is uses within if. We can say that if inside if. In this statement we use any above mentioned if statement inside the any true or false part of if.

Syntax

if(expression/condition)
                          if(expression/condition)                     
                                     statement;
                          else
                                     statement;        
              else
                          if(expression/condition)
                                     statement;

Here we can see that we use simple if and with else part if inside the if .

OR

if(expression/condition)
  {
                          Statement1;
                          Statement2;
                          ...
  Statement;
   
  If(expression)
  {          
                                      ....
                                      ....
  }          
  else if(expression/condition)
  {
                                      ...
  ...
  }
  }
  else
  {
                          
  Statement1;
                          Statement2;
                          ...
  Statement;
  If(expression) 
  {          
                                      ....
                                      ....
  }
  else if(expression/condition)
  {
                                      ...         
  ...
  }
  }

Listing 4: TestControlStatement.java

   
  public class TestControlStatement 
  {
              String playerName;
              int score;
  public TestControlStatement() 
              {
                          playerName=null;
                          score=0;
              }
   
              public void setPlayerName(String playerName)
              {
                          this.playerName=playerName;
              }
              public String getPlayerName()
              {
                          return this.playerName;
              }
              public void setScore(int score)
              {
                          this.score=score;
              }
              public int getScore()
              {
                          return this.score;
              }
              
              public String toString()
               {
                          return "\nPlayer Name :" + this.getPlayerName() +
                                      "\nScore       :" + this.getScore();
                }
              public void checkScore()
              {
                          
                          if(score >0 )
                          {
                                     if(score >=100)
                                     {
                                                 System.out.println("Bastman have make Century in This match");
                                     }
                                     else if(score >=50 )
                                     {
                                                 System.out.println("Bastman have make Fifty in This match");
                                     } 
                          }
                          else
                          {
                                     System.out.println("Batsman out Score of Zero (duck)");
                          }
                          
              }
              public static void main(String[] args)
              {
                          System.out.println("This is the Demo Nested if");      
                          TestControlStatement testControlStatement=new TestControlStatement();
                          testControlStatement.setPlayerName("ABC");
                          testControlStatement.setScore(51);
                          System.out.println(testControlStatement.toString());
                          testControlStatement.checkScore();
                          
                          testControlStatement.setPlayerName("XYZ");
                          testControlStatement.setScore(0);
                          System.out.println(testControlStatement.toString());
                          testControlStatement.checkScore();
              }
  }
  

OutputListing 4: TestControlStatement.java

This is the Demo Nested if

Player Name :ABC

Score :51

Bastman have make Fifty in This match

Player Name :XYZ

Score :0

Batsman out Score of Zero (duck)

Here, in above example we seen that the if inside the if . This is called a nested if.

Switch Statement

Switch Statement is used for select a single value from a multiple Condition or expression.We can also use switch in the case of checking multiple conditions on the single Expression. i.e we want to check character is vowel or not.

Syntax :

 switch(Expression)      
  {
              case value1:
                         //statements;
                         [break]; //Not Neccesory
              case value2:
  //statements;
  [break]; //Not Neccesory
              ....
  ...
  case valuen:
  //statements;
  [break]; //Not Neccesory
  default: //NotNeccesory
             //statements
  }

Listing 5: TestControlStatement.java

   
  public class TestControlStatement 
  {
              int score[];
                          
              public TestControlStatement() 
              {
                          score=new int[]{20,30,50,80,90,20,102,16,11,0,8};
              }
   
               public int getScore(int playerNo)
              {
                          int playerScore=0;
                          switch(playerNo)
                          {
                                     case 1:
                                                 playerScore=score[playerNo-1];
                                                 break;
                                     case 2:
                                                 playerScore=score[playerNo-1];
                                                 break;
                                     case 3:
                                                 playerScore=score[playerNo-1];
                                                 break;
                                     case 4:
                                                 playerScore=score[playerNo-1];
                                                 break;
                                     case 5:
                                                 playerScore=score[playerNo-1];
                                                 break;
                                     case 6:
                                                 playerScore=score[playerNo-1];
                                                 break;
                                     case 7:
                                                 playerScore=score[playerNo-1];
                                                 break;
                                     case 8:
                                                 playerScore=score[playerNo-1];
                                                 break;
                                     case 9:
                                                 playerScore=score[playerNo-1];
                                                 break;
                                     case 10:
                                                 playerScore=score[playerNo-1];
                                                 break;
                                     case 11:
                                                 playerScore=score[playerNo-1];
                                                 break;
                                                 
                                     default:
                                                 System.out.println("invalid No");
                          }
                          return playerScore;
              }
              public static void main(String[] args)
               {
                          TestControlStatement testControlStatement=new TestControlStatement();
                          System.out.println("Score of No 3 Player is :"+testControlStatement.getScore(3));
                          System.out.println("Score of No 9 Player is :"+testControlStatement.getScore(9));
                          System.out.println("Score of No 11 Player is :"+testControlStatement.getScore(11));
              }
  }

Output Listing 5: TestControlStatement.java

Score of No 3 Player is :50

Score of No 9 Player is :11

Score of No 11 Player is :8

Here, it is a simple example of switch case we store score of player in one array and retrieve it by using a switch case.

Repetition Statements

Repetitive Statements are used to do some repetitive task in our code. List of Repetitive Statements in Java is given below.

  • while Loop
  • do{}while Loop
  • for Loop

while Loop

while is the one of the most commonly used repetitive statement in java code. While loop iterates all the statements that are written inside it till the given condition is true.

Syntax:

 
  while(expression/condition)
  {
              //statement1;
  //statement2;
  ...
  //statement;
   
  }

Here ,in the Syntax ‘ while ‘ is the keyword and expression is any valid expression that is always a boolean.

Listing 6: TestControlStatement.java

   
  public class TestControlStatement 
  {          
      public TestControlStatement() {  }
   
      public static void main(String[] args)
      {
              int i=1;
              while(i<=10)
              {
                          System.out.println("Value of i is:"+i);
                          i++;
              }
      }
  }
  

Output Listing 6: TestControlStatement.java

Value of i is :1

Value of i is :2

Value of i is :3

Value of i is :4

Value of i is :5

Value of i is :6

Value of i is :7

Value of i is :8

Value of i is :9

Value of i is :10

Here in the example we can to say that while loop is executed until the condition is true. When it is false it stops the execution and execute the next code in the program.

We can make our while loop infinite by simply passing the true in the expression.

while(true)  //infinte Loop
  {
              Statement1;
              Statement2;
              ...
              ...
              Statementn;
  }

do{} while Loop

do{}while Loop is same as the while loop but while loop is entry control loop and do while loop is exit control loop. In the while loop it checks condition first then executes the next statement.in the do{}while loop it executes one time the code and then checks the condition.

Syntax :

do
  {
              Statement1;
              Statement2;
              ....
              ....
              Statement;
   
  }while(expression/condition);

Listing 7: TestControlStatement.java

  import java.util.*;
   
  public class TestControlStatement 
  {
              
      public TestControlStatement() 
      {
   
      }
   
      public static void main(String[] args)
      {
              Scanner sc=new Scanner(System.in);
              int selection;
              boolean  flag=true;
              do
              {
                                     System.out.println("Food Grain Menu :");
                                     System.out.println("\n\n\t1. Bajra ");
                                     System.out.println("\t2. Wheat ");
                                     System.out.println("\t3. Sorghum ");
                                     System.out.println("\t4. Exit ");
                                     System.out.print("\n\nEnter Your Choice :");
                                     selection=sc.nextInt();
                                     switch(selection)
                                     {
                                                 case 1:
                                                             System.out.println("You  Have Selected Bajara");
                                                             break;
                                                 case 2:
                                                             System.out.println("You  Have Selected Wheat");
                                                             break;
                                                 case 3:
                                                             System.out.println("You  Have Selected Sorghum");
                                                             break;
                                                 case 4:
                                                             flag=false;
                                                             break;
                                                             
                                                 default:
                                                             System.out.println("Wrong Selection");
                                     }
              }while(flag==true);
      }
  }
  

Output Listing 7: TestControlStatement.java

Food Grain Menu :

1. Bajra

2. Wheat

3. Sorghum

4. Exit

Enter Your Choice :2

You Have Selected Wheat

Food Grain Menu :

1. Bajra

2. Wheat

3. Sorghum

4. Exit

Enter Your Choice :3

You Have Selected Sorghum

Food Grain Menu :

1. Bajra

2. Wheat

3. Sorghum

4. Exit

Enter Your Choice :1

You Have Selected Bajara

Food Grain Menu :

1. Bajra

2. Wheat

3. Sorghum

4. Exit

Enter Your Choice :

4

for Loop

Syntax

  for(initialization; Expression/condition;increment)
   {
                 statement1;
                 statement2;
                 ...
                 ...
                 statementn;
  }

Here ‘for’ is the keyword of java used for looping. In initialization block we initialize the variable in expression/condition block we specify the condition for the loop and at the end we increase the value of our variable. All blocks in the for loop is optional.

Another Form of for Loop ( We can also call it enhanced for Statement in Java):

 
  for(declaration : expression)
  {
                 statement1;
                 statement2;
                 ...
                 ...
                 statementn;
   
  }

Different Form of For loop.

 
  int i=0;
  for(;i<10;i++){}
   
  for(i=0;i<10;)
  {
              i++;
  }
   
  for(;;){}  //infinate For loop
   
  for(i=0;;i++)
  {
              if(i==10)
                          break;
  }

Listing 8: TestControlStatement.java

   
   
  import java.util.*;
  public class TestControlStatement 
  {
              
              int score[];
              
      public TestControlStatement() 
      {
              score=new int[]{20,11,3,45,56,67,47,38,29,10,81};
      }
   
      public static void main(String[] args)
      {
              TestControlStatement testControlStatement=new TestControlStatement();
              System.out.println("This is the Demo of Simple For Loop");
              
              for(int i=0;i<11;i++)
              {
                          System.out.println("Score of The Player "+(i+1)+ " is :"+ testControlStatement.score[i]);
              }
              
              System.out.println("\n\nThis is the Demo of enhanced(Foreach) For Loop \n");
              int i=1;
              for(int value:testControlStatement.score)
              {
                          System.out.println("Score of The Player "+(i+1)+ " is :"+ value);
                          i++;
              }
      }
  }

Output Listing 8: TestControlStatement.java

This is the Demo of Simple For Loop

Score of The Player 1 is :20

Score of The Player 2 is :11

Score of The Player 3 is :3

Score of The Player 4 is :45

Score of The Player 5 is :56

Score of The Player 6 is :67

Score of The Player 7 is :47

Score of The Player 8 is :38

Score of The Player 9 is :29

Score of The Player 10 is :10

Score of The Player 11 is :81

This is the Demo of enhanced (Foreach) For Loop

Score of The Player 2 is :20

Score of The Player 3 is :11

Score of The Player 4 is :3

Score of The Player 5 is :45

Score of The Player 6 is :56

Score of The Player 7 is :67

Score of The Player 8 is :47

Score of The Player 9 is :38

Score of The Player 10 is :29

Score of The Player 11 is :10

Score of The Player 12 is :81

Branching Statements

There are mainly three kinds of Branching Statements:

  • break Statements
  • continue Statements
  • return Statements

break Statements

break statements are used for the break the loop or switch case.

There is mainly two kinds of break statements available in java language labelled and unlabelled breaking statement;

syntax

 
  break; //unlabeled break
  break label; // labeled break
  

unlabeled break

Listing 9: TestControlStatement.java

   
  import java.util.*;
  public class TestControlStatement 
  {
              
      public TestControlStatement() 
      {
              
      }
   
      public static void main(String[] args)
      {
              TestControlStatement testControlStatement=new TestControlStatement();
              System.out.println("This is the Demo of unlabeled break");
              
              for(int i=0;i<11;i++)
              {
                          System.out.println("Number i is  = "+i);
                          if(i==7)
                          {
                                     System.out.println("Break loop at Number 7");
                                     break;
                          }                      
              }
      }
  } 

Output Listing 9 : TestControlStatement.java

This is the Demo of unlabeled break

Number i is = 0

Number i is = 1

Number i is = 2

Number i is = 3

Number i is = 4

Number i is = 5

Number i is = 6

Number i is = 7

Break loop at Number 5

labeled break

Listing 10: TestControlStatement.java

   
  import java.util.*;
  public class TestControlStatement 
  {
              int empId;
              String contactNo[];      
               public TestControlStatement(int empId,String contactNo[]) 
              {
                          this.empId=empId;
                          this.contactNo=contactNo;
               }
   
              public static void main(String[] args)
              {
                          TestControlStatement testControlStatement[]=new TestControlStatement[]
                                     {new TestControlStatement(1,new String[]{"8765432190","9876543210"}),
  new TestControlStatement(2,new String[]{"9065432190","9116543210"}),
                                     new TestControlStatement(3,new String[]{"8265432190","9871143210"}),
                                     new TestControlStatement(4,new String[]{"8365432190","9876333210"}),
                                     new TestControlStatement(5,new String[]{"8565432190","9876223210"})
                                      };
              System.out.println("This is the Demo of labeled break");
              String search="9871143210";
              boolean flag=false;
              stop :    //break label
                          for(TestControlStatement temp : testControlStatement)
                          {
                          
                                     for(String no : temp.contactNo)
                                     {
                                                 if(no.equals(search))
                                                 {
                                                             flag=true;
                                                             System.out.println("Empoyee Id is :"+ temp.empId + " has this Contact no"+no);
  break stop;
                                                 }                      
                                     }
                          }
              
                          if(flag==false)
                          {
                                     System.out.println("Contact number not Found");
                          }
      }
  }
  

OutputListing 10: TestControlStatement.java

This is the Demo of labeled break

Empoyee Id is :3 has this Contact no 9871143210

Continue Statement

continue statement is used to continue loop in some condition and skip the particular code when the condition occurs.

There are mainly two kinds of continue statement

  • labeled
  • unlabeled

Labeled

In this continue statement we use the label to continue the loop. Here we provide label name with continue keyword to specify the position of continue code.

Syntax

            continue labelname;

Where continue is a keyword and label name is name of your part of code from where you want to continue your code.

Unlabeled

In this statement we use only continue keywords to continue our loop.

Syntax

           continue ;

Return Statement.

Return statement in java is used to return a value. Java uses return keyword for returning value from any part of code. Return statement puts your control at the position from where you call it.

In java method that has return type is used this statement to return some specific value. We can also write only single return keyword without specifying return value type.

Syntax:

            return;
              OR
              return [value];

OR

return [variable_name].

The first return statement is simple return without any value. Second and third return statements are similar.The second return value and the third return variable that has a value.

Conclusion

In this article we got brief idea about how control statements work in Java.. We illustrated all the control statements using examples.



Computer system engineer who has 4 year of experience in the field our web-development ,FPGA, and java programming.

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login