While Loop Java with examples
In The Last post of core Java tutorial series, we have discussed how to use for loop in java and this post, we are going to discuss while loop. As we mentioned in our previous post that we are using loops to execute some set of statements repetitively for some times until the condition is satisfied.
while loop Syntax
while (condition) { // codes inside the body of while loop }
How while loop works?
In While loop, the condition verified first, and it returns true value then the execution flows enter into the method body area and execute the statements. If the condition returns false, then the execution flow comes out from the loop and jump to the statements outside of while loop.
package java_Basics; public class Whileloop_Example { public static void main(String[] args) { int i = 1; while (i <= 10) { System.out.println("Value Of I:- " + i); ++i; } } }
Output:
Value Of I:- 1 Value Of I:- 2 Value Of I:- 3 Value Of I:- 4 Value Of I:- 5 Value Of I:- 6 Value Of I:- 7 Value Of I:- 8 Value Of I:- 9 Value Of I:- 10
Note:
During executing the while loop, we need to use an increment or decrement statement inside the loop body area so that the value of the variables changes regularly on each iteration and at some time the condition return false. In this way, we can end the execution of while loop; otherwise, the loop will run for indefinitely.
Ref: Article
Leave a Reply