Java While, Do While Loops Syntaxes, Examples and Real Time Uses
If we do not know the number of iterations in advance then the while loop is the best choice. The Java while loop can iterate infinite number of times. We can use while loop similar to for loop using a counter variable.
Syntax:
while(boolean_expression)
{
//statements
}
Example: Print 1 to 5 numbers
int i=1;
while(i<=5)
{
System.out.println(i);
i++;
}
Output:
1
2
3
4
5
Note: The argument to the while loop should be boolean type, if we provide any other type then we will get compiletime error.
while(1)
{}
Note: Curly braces are optional and without curly braces we can take only one statement which should not be declarative statement.
Example 1: Valid
while(true)
{
System.out.println("this is valid");
}
Example 2: Valid
while(true);
Example 3: Invalid
while(true)
int i=10;
Example 4: Valid
while(true)
{
int i=10;
}
Realtime Uses of while loop in Java programming
The uses of while loops are whenever we require unknown number of repetitions, some of them are listed below.
Example 1: To get the records from ResultSet in JDBC programming.
while(rs.next())
{
}
Example 2: To iterate the elements from legacy collections.
while(ele.hasMoreElements())
{
}
Example 3: To iterate the elements from collections.
while(itr.hasNext())
{
}
Java Do While Loop Syntaxes and Examples
If we want to execute a loop body atleast once then we should use do while loop. The body of do always execute first time without checking the condition in while but from second iteration it executes only if the condition in while becomes true.
Syntax:
do{
//statements
}while(boolean_expression);
Note: Semicolon ; at the end of while is mandatory
Note: Curly braces are optional and without curly braces we can take only one statement which should not be declarative statement.
Examples 1: Valid
do
System.out.println("valid do while");
while(true);
Example 2: Valid
do;while(true);
Example 3: Invalid
do
int i=10;
while(true);
Examples 4: Valid
do{
int i=10;
}while(true);
Example: Perform infinite arithmetic oprations.
import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System. in);
char op;
do{
System.out.println("***Choose an Operation***\n + Addtion \n - Subtraction \n / Division \n * Multiplication \n E Quit");
op = sc.next().charAt(0);
if(op=='e' || op=='E')System.exit(0);
System.out.println("Enter first number");
int a = sc.nextInt();
System.out.println("Enter second number");
int b = sc.nextInt();
switch(op)
{
case '+': System.out.println("Sum is "+(a+b));break;
case '-': System.out.println("Sub is "+(a-b));break;
case '/': System.out.println("Div is "+(a/b));break;
case '*': System.out.println("Mul is "+(a*b));break;
default : System.out.println("Invalid opration selected");
}
}while(op!='e' || op!='E');
}
}