While loop in Java

(Last Updated On: February 25, 2019)

Learn while loop in java programming with program examples and explanation with special notes. Demonstration of infinite while loop is included that run for ever.

Topics

  • Syntax of while loop with code example
  • Special note – semi colon after while ();{}
  • Infinite while loop

Syntax of a while loop in java:

 

In while condition, if Boolean expression evaluates to true, then
code block (under body of the while loop demonstrated by opening {and closing bracket} inside the loop will be executed.

Again, control goes back to start of the loop. Again, evaluate Boolean expression in while condition. if that is true, then run the same code block again.
Once the Boolean expression evaluate to false, the control will exit the loop and don’t go inside the while loop.

Java Code Example:
Print number from 1 to 10.

Output:
1
2
3
4
5
6
7
8
9
10

 

SPECIAL NOTE

Be careful with semi column [; ] after while () but before body. for example, while(n<1=10);{} as it may leads to application hang.

Details:

Consider below code example,

If you put semi column after while but before its body e.g. while(n<1=10);{} then control will run while (n <= 10); forever. As, while (n <= 10); becomes a statement.

The control will always find the expression true as its value is not getting increment and always be n =1.

 

 

Infinite while loop in Java

To run a while loop infinitely, just we need to write true in while condition e.g. while(true){…}.