Java Loops and Control Statements

In programming, if you want to repeat the execution of a particular set of instructions or want to execute a function/set of lines repeatedly then we use loops. For example, if you want to print a number 10 times, what would you do? Probably a newbie would write a 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 the picture. It's the most 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 the initialization of the variable. For loop gets executed until this condition is true. When this condition becomes false, the 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 gets 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 initializing an integer i with the value 1.
  2. Then we are checking whether the clause of i is less than or equal to 10 which is true, so the loop will be executed.
  3. Now, a code statement will be executed which prints i, which means 1 will be printed.
  4. Control will go to the increment operator now, and the value of i will be incremented by 1, which means i becomes 2.
  5. Then the loop will execute above 1 to 4 steps until the value of i becomes 10. When it's value will become 10 then the 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 an array or collection.

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

Let's take an example, say you have an array of strings having 5 car names and you want to print all the car names. We can do that using a 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 the first value from the cars which is "Jeep" and print it.
  4. Then it again gets the second value from the car array which is "BMW" and prints it and so on until the last value of the array.
Output:
Jeep
BMW
Ford
Mazda
Jaguar

3. 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 a loop.

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

Let's understand with an example, we want to print 1 to 10 numbers using a while loop. Below is the code 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 a condition that executes 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 the 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


4. Do While Loop

It is similar to a 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 at least once and its next execution 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 of whether x is less than 25 which is false and the loop will exit after printing the x only once.
Output:
Value of x: 25

Click here to find the complete Java Tutorials Series

Java Conditional Statements  << Previous     ||     Next >>  Java OOPS Concepts

Author
Vaneesh Behl
Passionately writing and working in Tech Space for more than a decade.

Comments

Popular posts from this blog

What Role Graphic Design Services Play in Marketing

Python Behave Tutorial: A Comprehensive Guide to Behavior-Driven Development (BDD)

Top 10 Highly Paid Indian CEOs in the USA

Testing a Web Page/Website: Best Practices for Quality Assurance and Improved User Experience

Automating Native Mobile Apps with Appium Commands

How to Solve Easily the Reader-Writer Locks in Golang

17 Best Demo Websites for Automation Testing Practice

Mastering Selenium Practice: Automating Web Tables with Demo Examples

Complete Guide to Software Testing Levels: From Unit to End-to-End Testing

Real-World Examples and Demo Scripts in Selenium Python Automation