Loop Control Statements in Java – For, While, Do While, Enhanched For Loop

HOME

Syntax

for(Variable Initialization; Boolean_Expression Test; Increment/Decrement){
   //Statements
    }
 
    for (int i = 0; i < 5; i++) {
    System.out.println(i);
    }

Example

   public class For_loop {
     public static void main(String[] args) {
       for(int i=0;i<5;i++)
    {
       System.out.println("Value of i is: "+i);
    }
   System.out.println("-----------------------------------------------------");
       for (int j=5;j>0;j--)
       {
              System.out.println("Value of j is: "+j);
        }
     }
   }
 
Output
Value of i is: 0
Value of i is: 1
Value of i is: 2
Value of i is: 3
Value of i is: 4
--------------------------------------------------------
Value of j is: 5
Value of j is: 4
Value of j is: 3
Value of j is: 2
Value of j is: 1
  •    Statement 1 sets a variable before the loop starts (int i = 0).
  •    Statement 2 defines the condition for the loop to run (i must be less than 5). If the condition is true, the loop will start over again, if it is false, the loop will end.
  •    Statement 3 increases a value (i++) each time the code block in the loop has been executed.

2) While Loop

 The Java while loop is used to iterate a part of the program several times. If the number of iteration is not fixed, it is recommended to use while loop.

Syntax

   while(Boolean_Expression Test)
    {
        //Statements
    }

Example

  public class While_Loop {
    public static void main(String[] args) {
       int i=0;
       while (i<15)
       {
            i=i+3;
            System.out.println("Value of i is :"+i);
         }
  System.out.println("--------------------------------------------"); 
  // In this case, value of j will be 0 and it will run infinite times. 
    int j=0;
    while(j<15)
    System.out.println("Value of j is :"+j);
    {
       j=j+3;
    }
  }
 }

Output
Value of i is :3
Value of i is :6
Value of i is :9
Value of i is :12
Value of i is :15
--------------------------------------------
Value of j is :0
Value of j is :0

3) What is the difference between for and while loop?

While loop is used in situations where we do not know how many times loop needs to be executed beforehand.
For loop is used where we already know about the number of times loop needs to be executed. Typically for a index used in iteration.

4)  Do While Loop

A do while loop is exactly similar to while loop and the only difference between two is that the do while loop executes the statement at least one time. As it start with do keyword and the boolean expression appears at the end of the loop.

Syntax

   do{
         //Statements
       }while(Boolean_Expression Test);

Example

public class Do_While_Loop {
       public static void main(String[] args) {  
         int i=0;
          do 
          {
             i=i+3
             System.out.println("Value of i is :"+i);
           }
           while (i<15);
           System.out.println("-------------------------------------------");
           //Condition is already satisfied, still 1 round of execution
           int j=10;
           do
          {
            j=j+2;
            System.out.println("Value of i is :"+j);
           }
       while (j<10);
       }
   } 
   
Output
Value of i is :3
Value of i is :6
Value of i is :9
Value of i is :12
Value of i is :15
-----------------------------------------------------
Value of i is :12

5) What is the difference between While Loop or do- while loop?

1) while loop first check the condition then enter the body whereas do-while first enter the body and then check the condition.
2) while is a entry controlled loop whereas do-while is an exit controlled loop.
3) In while, condition comes before the body whereas in do-while, condition comes after the body.

6) Enhanced for loop in Java

 It is used to traverse array or collection in java. It is easier to use than simple for loop because we don’t need to increment value and use subscript notation.

It works on elements basis, not index. It returns element one by one in the defined variable.

Syntax

for (data_type variable: array_name)

Example

public class Enhanced_Loop {
       public static void main(String[] args) {

          // Array of String storing days of the week
           String days[] = { "Mon", "Tue", "Wed", "Thr", "Fri", "Sat", "Sun"};
           
           // Enhanced for loop, this will automatically iterate on the array list 
           for (String dayName : days) 
          {
             System.out.println("Days ==> "+ dayName);
           }
             System.out.println("");
             
             // Normal for loop
           for (int i=0; i < days.length; i++) {
               System.out.println("Days ==> "+ days[i]);
           }
       }
   }

Output
Days ==> Mon
Days ==> Tue
Days ==> Wed
Days ==> Thr
Days ==> Fri
Days ==> Sat
Days ==> Sun 
 
Days ==> Mon
Days ==> Tue
Days ==> Wed
Days ==> Thr
Days ==> Fri
Days ==> Sat
Days ==> Sun

Decision Making in Java – If, If Else, Switch, Break, Continue

HOME
  

Decision making in Java is same as real life decision making. I remember during my childhood, my father had told me once that if I get 1st rank in class will get a bicycle, else if 2nd will get a walk man, else if 3rd video game else nothing. This is an ideal example of if-else scenario. If a particular condition is true, then execute the specified block of code. In programming language too, we execute certain lines of code if the condition is satisfied. In programming language too, we follow the similar concept, such as

• Block of code to be executed, if a specified condition is true
• Use else to specify a block of code to be executed, if the same condition is false
• Use else if to specify a new condition to test, if the first condition is false
• Use switch to specify many alternative blocks of code to be executed

The if condition 

if (condition) {
    // block of code to be executed if the condition is true
public class Java_Demo {
    public static void main(String[] args) {
        int x=50;
        int y=10;
       
	    if(x>y)
       {
            System.out.println("x is greater than y");
       }
    }
}

Output
x is greater than y

 If we do not provide the curly braces ‘{‘ and ‘}’ after if(condition ) then by default if statement will consider the immediate one statement to be inside its block. For example,

if(condition)
     statement1;
     statement2;

  // Here if the condition is true, if block will consider only statement1 to be inside its block.

     Use the else statement to specify a block of code to be executed if the condition is false.

The else Statement

if (condition) {
    // block of code to be executed if the condition is true
   } else { 
    // block of code to be executed if the condition is false
   } 
 public class Java_Demo {
     public static void main(String[] args) {
         int x=5;
         int y=10;
         if(x>y)
            {
                System.out.println("x is greater than y");
            }
          else
            {
                System.out.println("y is greater than x");
            }
        }
    }

Output
y is greater than x

The else if Statement Use the else if statement to specify a new condition if first condition is false.

If (condition1) {
     // block of code to be executed if condition1 is true
   } else if (condition2) {
    // block of code to be executed if the condition1 is false and condition2 is true
   } else {
    // block of code to be executed if the condition1 is false and condition2 is  false
   }
public class Java_Demo {

	public static void main(String[] args) {
		int x = 10;
		int y = 10;
		if (x > y) {
			System.out.println("x is greater than y");
		} else if (y > x) {
			System.out.println("y is greater than x");
		} else {
			System.out.println("x is equal to y");
		}
	}
}

Output
x is equal to y

Switch Statement

  • The switch expression is evaluate once.
  • The value of the expression is compare with the values of each case.
  • If there is a match, the associated block of code is execute.
  • The break and default keywords are optional

    Use the switch statement to select one of many code blocks to execute. It is use to replace multilevel if-else-if statement. 
However, the switch statement can be use only if the conditions based on the same constant value.

  switch(expression) {
       case x:
      // code block
       break;
       case y:
     // code block
       break;
      default:
      // code block
   }

 The default statement is use as the last statement in a switch block; it does not need a break.

 When Java reaches a break keyword, it breaks out of the switch block.

public class Switch_Statement {
    public static void main(String[] args) {
		int month_no = 3;
		switch (month_no) {
		case 1:
			System.out.println("January");
			break;
		case 2:
			System.out.println("February");
			break;
		case 3:
			System.out.println("March");
			break;
		case 4:
			System.out.println("April");
			break;
		case 5:
			System.out.println("May");
			break;
		case 6:
			System.out.println("June");
			break;
		default:
			System.out.println("Rest of months");
		}
	}
}

Output
March

Default Keyword

The default keyword specifies that specific code will run if there is no case match.

public class Default_Demo {

	public static void main(String[] args) {
		int month_no = 9;
		switch (month_no) {
		case 1:
			System.out.println("January");
			break;
		case 2:
			System.out.println("February");
			break;
		case 3:
			System.out.println("March");
			break;
		case 4:
			System.out.println("April");
			break;
		case 5:
			System.out.println("May");
			break;
		case 6:
			System.out.println("June");
			break;
		default:
			System.out.println("Rest of months");
		}
	}
}

Output
Rest of months

Break Statement

 It terminates the loop by skipping the execution of any remaining code

public static void main(String[] args) {
    for(int i=0;i<5;i++)
      {
         if(i==2)
         break;
         System.out.println("Value of i is: "+i);
       }
         System.out.println("Loop finishes");
     }
   }

Output
Value of i is: 0
Value of i is: 1
Loop finishes

Continue Statement


It continue running the loop, just skip a particular iteration of the loop.

public class Continue_Demo {
   public static void main(String[] args) {
        for(int i=0;i<5;i++)
         {
             if(i==2)
             continue;
             System.out.println("Value of i is: "+i);
           }
         System.out.println("Loop finishes");
     }
  }

Output
Value of i is: 0
Value of i is: 1
Value of i is: 3
Value of i is: 4
Loop finishes