Java Loops and Control Statements

In programming if you want to repeat the execution of particular set of instructions or want to execute a function/set of lines repeatedly then we use loops. For example you want to print a number 10 times, what would you do? Probably a newbie would write print statement 10 times, but we can do the same thing to use a loop. Let's understand the different types of loops with examples.

  • For loop
  • For-each loop
  • While loop
  • Do-While loop
1. For Loop
When you know that you want to execute your code fixed no. of times say 10 times, then for loop comes into picture. It's the mostly used and the simplest loop in any programming. Here is the For loop structure:

for(initializing variable; condition; increment/decrement)
	{
		// Code/Statement to be iterated
	}

It has four different elements, let's understand them:
  1. Initialization Variable - It is the starting point of the for loop. This variable gets initialized when for loop gets started.
  2. Condition - It comes into play after initialization of variable. For loop gets executed until this condition is true. When this condition becomes false, loop exits.
  3. Increment/Decrement - It is used for incrementing or decrementing the variable that we initialized at the beginning of the loop.
  4. Statement - It is the code/set of instructions written inside the loop that we want to execute N number of times until our condition get false.
Now it's time to understand it by a code example, let's say you want to print numbers 1 to 10. Let's see the code to understand how we can use for loop to do that.

Example Code:

//Java Program to print 1 to 10 numbers using for loop  

public class LoopExample {  

	public static void main(String[] args) {  

		// For loop  to print numbers 1 to 10
		for(int i=1; i<=10; i++){
	  
			System.out.println(i);  

		}  
	}  
}  

Explanation of the code:
  1. We are initialising an integer i with value 1.
  2. Then we are checking whther the caluse of i is less than or equla to 10 which true, so the loop will be executed.
  3. Now, code statement will be executed which to print i, means 1 will be printed.
  4. Control will go to the increment operator now, and value of i will be incremented by 1, means i becomes 2.
  5. Then loop will execute above 1 to 4 steps until value of i becomes 10. When i's value will become 10 then loop will be exited and our program execution will be completed.
Output:
1
2
3
4
5
6
7
8
9
10


2. For-each loop
It is the enhanced version of for loop. It is used to iterate/loop over the elements of an array or other Java Collection object like list, arraylist etc. It has a different structure than for loop. It returns the elements one by one of a an array or collection.

for(DataType variable : ArrayName)
	{    
		//code to be executed    
	}    

Let's take an example, say you have an array of string having 5 car names and you want to print all the car names. We can do that using for each loop easily.

Example Code:

// Array
String[] cars = {"Jeep", "BMW", "Ford", "Mazda", "Jaguar"};

// For each loop
for (String str : cars) {
  System.out.println(str);
}

Explanation of the code:
  1. We have an array with five string elements which are basically car names/brands.
  2. We initialized a variable str of data type string then we have arrays cars.
  3. String str will get first value from cars which is "Jeep" and print it.
  4. Then it again get second value from cars array which is "BMW" and print it and so on until the last value of the array.
Output:
Jeep
BMW
Ford
Mazda
Jaguar


While loop
It executes a block of code or set of statements repeatedly or multiple times until a given condition is true. As soon as the condition becomes false it exits. It has a much simpler syntax wrt for loop.

while (boolean condition)
	{
	   // loop statements...
	   
	   // Increment/Decrement
	}

Let's understand with an example, we want to print 1 to 10 numbers using while loop. Below is the code for for same.

Example Code:

// Java Program to print 1 to 10 numbers using while loop

public class WhileClass {  

	// Main method
	public static void main(String[] args) {  
		
		// Initialise varibale
		int i=1;  

		// While loop
		while(i<=10){  
			// Code Statement
			System.out.println(i);  
		// Increment
		i++;  

		}  
	}  
}  

Explanation of the code:
  1. We initialized a variable i with value 1.
  2. We have declared as condition that execute this loop until the value of i is less than or equal to 10.
  3. Print value of i.
  4. Increment the value of i, it will become 2 after first execution.
  5. It will again check the condition and repeat the above steps 1 to 4 until i becomes 10 and finally exits the loop.
Output:
1
2
3
4
5
6
7
8
9
10


Do While Loop
It is similar to while loop the only difference is that it has a do block also and it executes the do block statement and then checks the condition.

do
{
    statement
}
while (condition);

As you can see do statement will be executed at any cost here for at least once and it's next executions depends on the condition, whether it's true or false.

Example Code:

// Java Program to understand do-while loop

public class DoWhileLoop{
    
	public static void main(String args[])
    {
        int x = 25;
    
		// Do-While Loop
		do
			{
				// The line will be printed even
				// if the condition is false
				System.out.println("Value of x:" + x);
				
				// Increment
				x++;
			}
        while (x < 20);
    }
}

Explanation of the code:
  1. Initialized a variable of type int as 25.
  2. Do statement to print x.
  3. And then check the condition whether x is less than 25 which is false and the loop will exit after printing the x only for once.
Output:
Value of x: 25

Click here to find complete Java Tutorials Series

Java Conditional Statements  << Previous     ||     Next >>  Java Object and Class



Follow Us

Quora Space | Facebook Page | Telegram Channel
Feel free to ask queries or share your thoughts in comments or email us.

Comments

Popular posts from this blog

10 Best Demo Websites for Automation Testing Practice

Automate E-Commerce Website using Selenium Webdriver

Automate Browser Actions on Godaddy.com using Selenium

Automate Amazon Website 'Menu links' using Selenium