Tuesday, January 14, 2014

# 8 Java Looping Techniques

Hello,

Happy Pongal and Makara Sankranthi to everyone..! :)

In this post I am going to explain you the most important Java concept - Looping Statements.
Looping Statement - is the process which helps the developer to write a single statement and execute it multiple times. 

Java supports 3 kinds of looping techniques.

  1. while loop
  2. do-while loop
  3. for loop

Let us see in detail about each looping technique.

while loop:
The syntax of the while loop is as follows,
while(expression){
// your code goes here
}
The expression in the brackets needs to be returned a Boolean value. Depending on the Boolean value the code executes.
If the expression returns true, then control goes inside and execute the code.
If the expression returns false, then the control will come out of the loop.

The below example explains you more. I would like to print numbers for 1 to 10 using while loop.
public static void main(String[] args)
{
	int i = 1;
	while (i <= 10)
	{
		System.out.print("" + i);
     		i = i+1; // or i++       
	}
	System.out.println();
	System.out.println("i value is "+i+" hence While condition failed and stopped looping..!");
}

Output : 

12345678910
i value is 11 hence While condition failed and stopped looping..!
Here what you need to understand is, the code inside the while loop is executed till i value is less than or equal to 10. When the i value has become 11, the condition in the brackets failed and the loop has ended.

Note – Remember the above program because I will be using the same program to explain you the for loop. 

do-while loop :

The syntax for the do-while loop is as follows.
do {
     // your code goes here
} while (expression);
The working of the do-while loop is very much similar to the while loop. It takes a boolean expression and executes the code if the condition is true or else exit from the loop.

The only difference between the while loop and do-while loop is,
Do-while loop executes the code and then evaluates the expression where as the while loop evaluates the expression and then executes the code if and only if the expression returns true.

Below example gives you clear idea about the difference.
public static void main(String[] args)
{
	int i = 1;
	System.out.println("i value is --> "+i);
	do
	{
   		System.out.println("Inside the loop :: ");
   		System.out.println(""+i);
   		i++; //i = i+1;        
	}while(i<0);
  	
	System.out.println("i value is "+i+" hence While condition failed and the control came out of the loop..!");
}

Output:

i value is --> 1
Inside the loop :: 
1
i value is 2 hence While condition failed and the control came out of the loop..!
Here, initially the i value is 1. The control entered into the “do” block executed the code and then started evaluating the expression. The condition fails and exited from the loop.
Now let us try to execute the same program with while loop and let us observe the output.
public static void main(String[] args)
{
	int i = 1;
	System.out.println("i value is --> "+i);
	
	while(i<0)
	{
		System.out.println("Inside the loop :: ");
		i++; //i = i+1;
        }
 	
	System.out.println("i value is "+i+" hence While condition failed and the control came out of the loop..!");
}

Output:

i value is --> 1
i value is 1 hence While condition failed and the control came out of the loop..!
In the while loop, the control didn't enter inside the loop because the expression evaluated first and the expression returned false and exited the while loop.

for-loop :

for-loop is my favorite looping technique. Not only me, but also many developers would like to choose for loop if they have to choose a looping technique.
The for-loop helps the code more readable and the syntax for the for-loop is as follows.
for (initialization; termination; increment){
// your code goes here
}
int i = 1; // this is called initialization. 
I had declared and initialized the variable “i”. This executes only once (first time) in the for loop.
Termination - 
Here goes the expression which returns a boolean value. The loop continues until and unless the expression returns false.
Increment - 
Here goes the increment or decrement of the value which supports looping.

Now I am trying to write the program using for-loop that I have already written using while loop.
public static void main(String[] args){
   for(int i=1;i<=10;i++){
   System.out.print(""+i);
   }
 System.out.println();
 System.out.println("The expression failed and the control came out of the for loop..!");
 }

Output : 12345678910.
See here the entire code in the while loop can be replaced by a single statement in for-loop which is more readable.
int i = 1; 
while (i <= 10) {
 System.out.print("" + i);
 i = i+1; // or i++       
 }
for(int i=1;i<=10;i++){
 System.out.print(""+i);
}
There is another way to use the for loop which is called Enhanced for-loop. This has been introduced in Java 1.5 This enhanced for-loop is used mainly when Collections or Arrays are involved. You will learn more about Collections and Arrays in future posts. For now, we will see an example how to iterate an array of integers using enhanced for loop.
public static void main(String[] args)
{
	int[] numberArray = {1,2,3,4,5,6,7,8,9,10}; // array declared and defined
        
	// enhanced for loop
	for (int j : numberArray)
	{ 
	System.out.print("" + j);
  	}
}

Output : 12345678910.
You can see that the loop ends after iterating all the elements in the array. After 10 there is no element in the array and hence the loop stopped.
//Internally when we write the below code,
for (int j : numberArray){}

//the compiler will convert it as,
for(int i=1;i<=numberArrySize;i++)
{
	j=a[i];
}
Hit Points :

  1. Use the looping techniques when you want to execute a statement multiple times.
  2. while loop executes the expression and if it returns true then only the code inside the loop executes.
  3. do while executes the code for the first time and then evaluates the expression. If the expression returns true then again it executes the code until and unless expression returns false.
  4. for-loop is a powerful technique among all the looping techniques.
  5. Enhanced for-loop is more convenient when Collections or Arrays are involved.
  6. Make sure while you are using the looping techniques, the loop doesn't go for infinity. Sometimes it may crashes JVM..!


Thanks for taking the time to stop by! :)

0 comments:

Post a Comment