A Complete Java Loops and Control Statements Tutorial

Java Loops

 
A loop in a computer program is an instruction that repeats until a specified condition is reached. In a loop structure, the loop asks a question. If the answer requires action, it is executed. The same question is asked again and again until no further action is required.
 

Entry Controlled Loop vs Exit Controlled Loop

  1. In an entry controlled loop, the test condition is checked first followed by loop body, whereas in an exit controlled loop, the loop body is executed first followed by the test condition
  2. In an entry controlled loop, if the test condition is false, the loop body will not be executed, whereas in exit controlled loop, if the test condition is false, the loop body will be executed once.
  3. Entry controlled loops are used when checking of test condition is mandatory before executing loop body, whereas exit controlled is used when checking of test condition is mandatory after executing.
  4. For loop, Foreach loop and while loops are examples of entry controlled loops, whereas do-while loop is an example of exit controlled loop.

Types of Java Loops

 

1. For Loop

 
Syntax
 
for(initialization condition; testing condition; increment/decrement)
{
            statements(s)
 
It is a type of loop that is used if the number of iterations is fixed i.e we know the starting and endpoint of the loop.
  1. import static java.lang.System.out;  
  2.   
  3. class Csharpcorner              
  4. {              
  5.     public static void main(String[] args)          
  6.     {                     
  7.        for(int i=0; i<10; i++)  
  8.        {  
  9.            out.println(i);  
  10.        }  
  11.    }              
  12. }          
In the above code, we are printing numbers from 0 to 9 using java for a loop.
 

2. ForEach Loop

 
Syntax
 
for (type var: array)
{
         statements(s)
}
 
It is a special version of Java For Loop, where instead of declaring and initializing a loop counter variable, you declare a variable that is the same type as the base type of the array, followed by a colon, which is then followed by the array name.
  1. import static java.lang.System.out;  
  2.   
  3. class Csharpcorner              
  4. {              
  5.     public static void main(String[] args)          
  6.     {              
  7.        String ch[] = {"CSharpCorner "};  
  8.          
  9.        for (String j:ch)  
  10.        {  
  11.            out.println(j);  
  12.        }  
  13.          
  14.     }                
  15. }      
In the above code, we are using the for each loop to print the character array.
 

3. While Loop

 
Syntax
 
while( condition)
          Statements
}
 
While loop is a type of loop that is used when the number of iterations is not fixed i.e ether of start point and endpoint is not known
  1. import static java.lang.System.out;  
  2.   
  3. class Csharpcorner              
  4. {              
  5.     public static void main(String[] args)          
  6.     {              
  7.         int i=0;  
  8.         while (i<10)   
  9.         {  
  10.             out.println(i);  
  11.             i++;  
  12.         }  
  13.     }                
  14. }   
In the above code, we are printing numbers from 0 to 9 using the while loop. 
 

4. Do-While Loop

 
Syntax
 
do
          statement(s)
}while    
 
It is a type of Java Loop which is used if the number of iterations is not fixed and we need to execute the loop body at least once.
  1. import static java.lang.System.out;  
  2.   
  3. class Csharpcorner              
  4. {              
  5.     public static void main(String[] args)          
  6.     {              
  7.         int i=0;  
  8.         do  
  9.         {  
  10.             out.println(i);  
  11.             i++;  
  12.         } while (i<10) ;  
  13.     }                
  14. }    
The above code demonstrates, the printing of numbers from 0 to 9 using a do-while loop
 

Java Infinite Loops

  1. An infinite loop is a piece of code that lacks a functional exit so that it repeats indefinitely. 
  2. It may be sometimes endless
  3. It may cause the system to crash or hang.
  4. Mostly arises due to a programming error.
  5. Ctrl-C or forced exit is the mechanisms used to break off an infinite loop.
  6. They are mostly used as a mechanism to achieve busy waiting

    1. Infinite loop using for loop
    1. import static java.lang.System.out;  
    2.   
    3. class Csharpcorner              
    4. {              
    5.     public static void main(String[] args)          
    6.     {              
    7.         for(;;)  
    8.         {  
    9.             out.println("1");  
    10.         }  
    11.     }                
    12. }   
         2. Infinite loop using while loop
    1. import static java.lang.System.out;  
    2.   
    3. class Csharpcorner              
    4. {              
    5.     public static void main(String[] args)          
    6.     {              
    7.         while(true)  
    8.         {  
    9.             out.println("1");  
    10.         }  
    11.     }                
    12. }    
         3. Infinite loop using a do-while loop
    1. import static java.lang.System.out;  
    2.   
    3. class Csharpcorner              
    4. {              
    5.     public static void main(String[] args)          
    6.     {              
    7.         do  
    8.         {  
    9.             out.println("1");  
    10.         }while(true);  
    11.     }                
    12. }     

Java Control Statements

 
Java Control statements are java keywords which are used for controlling the flow of the java program.

1. If statement

 
Syntax
 
if(condition)
{
   statements;
}
 
If the condition is true then the body will get executed otherwise nothing will happen.
  1. import static java.lang.System.out;    
  2.     
  3. class CSharpCorner                
  4. {                
  5.     public static void main(String[] args)            
  6.     {        
  7.         int i=0;  
  8.         if (i<5)   
  9.         {  
  10.             out.println(i);  
  11.         }  
  12.     }                  
  13. }       
In the above code, if the above condition is met then only 'i' is printed
 

2. if-else statement

 
Syntax
 
if(condition)
{
    statement;
}
else
{
   statements1;
}
 
This statement checks if the given condition is met then the statement is executed otherwise statements are executed
  1. import static java.lang.System.out;    
  2.     
  3. class CSharpCorner                
  4. {                
  5.     public static void main(String[] args)            
  6.     {        
  7.         int i=0;  
  8.         if (i<5)   
  9.         {  
  10.             out.println(i);  
  11.         }  
  12.         else  
  13.         {  
  14.             out.println(i/2);  
  15.         }  
  16.     }                  
  17. }       
In the above, if the given condition is met then 'i' is printed otherwise 'i/2' is printed
 

3. If-Else-If Statement

 
Syntax
 
if(condition)
{
   statement;
}
else if
{
   statements1;
}
else
{
   statements2;
}
 
Here in this, if the first condition is met then the statement is executed, otherwise, if the second condition is met the statements is executed, statments2 is finally executed.
  1. import static java.lang.System.out;    
  2.     
  3. class CSharpCorner                
  4. {                
  5.     public static void main(String[] args)            
  6.     {        
  7.         int i=0;  
  8.         if (i<5)   
  9.         {  
  10.             out.println(i);  
  11.         }  
  12.         else if (i>5)  
  13.         {  
  14.             out.println(i/3);  
  15.         }  
  16.         else  
  17.         {  
  18.             out.println(i/2);  
  19.         }  
  20.     }                  
  21. }       
In the above code if i is less than 5 then i is printed, otherwise, if i is greater than 5 than i/3 is printed, i/2 is printed
 

4. Nested if-else-if statements

 
Syntax 
 
if(condition)
{
statement;
}
else if
{
statements1;
}
else if
{
statements1;
}
.
.
.
else
{
statements2;
}

This will check the all the conditions one by one and the code corresponding to the met condition will get executed, otherwise, the code corresponding to else will get executed.
  1. import static java.lang.System.out;  
  2.   
  3. class Csharpcorner              
  4. {              
  5.     public static void main(String[] args)          
  6.     {              
  7.         int i=0;  
  8.         if(i==0)  
  9.         {  
  10.             out.print(0);  
  11.         }  
  12.         else if(i<5)  
  13.         {  
  14.             out.print("lesser");  
  15.         }  
  16.         else if(i>5)  
  17.         {  
  18.             out.print("greater");  
  19.         }  
  20.         else  
  21.         {  
  22.             out.print(i);  
  23.         }  
  24.     }                
  25. }                       
In the above code, we will be parsing though all of the conditions one by one and will be printing the corresponding output.
 

5. Switch Case Statements 

 
Syntax 
 
Switch(variable)
{
    case 0:
       .
       .
       . 
    case n-1:
    default:
 
This is a type of control statement in which we are a single variable is checked for multiple values and if neither value matches the code corresponding to default is executed.
  • Switch case does not allow variables to be taken as the case value. 
  • Only uniques case values are acceptable. 
  • Each case is suffixed by a break statement, to make sure that only the matched case code executes
  1. import static java.lang.System.out;  
  2.   
  3. class Csharpcorner              
  4. {              
  5.     public static void main(String[] args)          
  6.     {              
  7.         int i=0;  
  8.         switch(i)  
  9.         {  
  10.             case 0:   
  11.             case 1:  
  12.             case 2:   
  13.             case 3:  
  14.             case 4:  
  15.             case 5:  
  16.             case 6:out.print(i);  
  17.                     break;  
  18.             default: out.print("No value");                     
  19.         }  
  20.     }                
  21. }                       
In the above code, we are checking if i is between 0 to 6, if it is between then printing the i value, otherwise printing the text
 

6. Break Statement 

 
Syntax
 
java Statement
break;
 
The Java break is used to break the loop or switch statement. It breaks the current flow of the program at a specified condition.  
  1. import static java.lang.System.out;  
  2.   
  3. class Csharpcorner              
  4. {              
  5.     public static void main(String[] args)          
  6.     {              
  7.         for (int i = 0; i < 10; i++)   
  8.         {  
  9.             if (i>4)  
  10.                 break;  
  11.             else  
  12.                 out.print(i);  
  13.         }  
  14.     }                
  15. }  
The above code will output numbers from 0 to 3 and when it encounters 4 it will terminate the loop. 
 

7. Continue Statement 

 
Syntax
 
Jump statement
continue; 
 
The Java continue statement is used to continue the loop. It continues the current flow of the program and skips the remaining code at the specified condition. In case of an inner loop, it continues the inner loop only.
  1. class Csharpcorner              
  2. {              
  3.     public static void main(String[] args)          
  4.     {              
  5.         for (int i = 0; i < 10; i++)   
  6.         {  
  7.             if (i>4 && i<7)  
  8.             {  
  9.                 continue;  
  10.                   
  11.             }  
  12.             else  
  13.                 out.print(i);  
  14.         }  
  15.     }                
  16. }      
The above code will print all numbers from 0 to 9 except 5 & 6 as they satisfies the given condition.
 

Conclusion 

 
In the above article, we learned about Java Loops, difference between entry controlled and exit controlled loops, Types of Loops, For loop, for each loop, while loop, do-while loop, Java Infinite Loops, Java Controlled Statements, if, if-else, if-else-if, nested if-else, switch-case, break, continue and java implementation of each



C# Corner
MVP Program Director