Basic Java – 12 || Alternate looping concepts while and do-while. (Loops Part-2)

           While and do-while are two more alternates of for loop in Java. The only representation of these statements is different.

while Loop

while Loop
while Loop

          While loop consists only one parameter, based on that it repeats the instructions given in while block.

       A while loop first checks the condition and then executes the instruction given in the block.

Code Example-1:

public class WhileExample {

	public static void main(String[] args) 
	{
		int counter=1;
		// First checks the condition then executes the code block.
		while(counter<=5)
		{
			System.out.println(counter);
			counter++; 
		}
	}
}

Output:
1
2
3
4
5

do-while Loop

do-while Loop
do-while Loop

           The key difference between while and do-while loop is that while loop first checks the condition then executes the code block. On the other hand do-while loop first executes the code block then checks the condition.

In this case, code of block would execute at least once.

Code Example:

public class DoWhileExample2 {

	public static void main(String[] args) 
	{
		int counter=1;
		do
		{
			// First executes the code block then checks the condition.
			System.out.println(counter);
			counter++; 
		}while(counter<=5);
	}
}

Output:
1
2
3
4
5

Difference between while and do-while loop:

public class WhileExample {

	public static void main(String[] args) 
	{
		int counter=1;
		while(counter<=0)
		{
			System.out.println("Value of counter: "+counter);
			counter++; 
		}
		System.out.println("End of Program.");
	}
}

Output:
End of Program.
public class DoWhileExample {

	public static void main(String[] args) 
	{
		int counter=1;
		do
		{
			System.out.println("Value of counter: "+counter);
			counter++; 
		}while(counter<=0);
		
		System.out.println("End of Program.");
	}
}

Output:
Value of counter: 1
End of Program.

1827total visits,2visits today

Leave a Reply

Your email address will not be published. Required fields are marked *