While loop in java
Understanding while loop in Java
- While loop works very similar to for loop.
- The only difference between for loop and while loop is the positioning of initialization, evaluation and expression evaluation section.
- While loop only takes boolean Type as the condition argument OR an expression resulting in a boolean value. Any other Type like int , long is not acceptable.
Lets take examples to understand while loop
- Classical while loop
public void loop1() {
// initialization
int i = 2;
// condition check
while (i >= 0) {
System.out.println("Inside LOOP1 value of i is " + i);
i--; // expression evaluation
}
}
Inside LOOP1 value of i is 2
Inside LOOP1 value of i is 1
Inside LOOP1 value of i is 0
[addToAppearHere]
- Infinite While loop
public void loop2() {
// infinete while loop
// condition check
while (Boolean.TRUE) {
System.out.println("Inside infinite while loop");
}
}
- While loop with a method in the conditional check
private int getConditionaValue() {
System.out.println("I am inside the getConditionaValue method");
return 0;
}
public void loop3() {
int i = 3;
// condition check
while (i >= getConditionaValue()) {
System.out.println("Inside LOOP3 value of i is " + i);
i--;
}
}
I am inside the getConditionaValue method
Inside LOOP3 value of i is 3
I am inside the getConditionaValue method
Inside LOOP3 value of i is 2
I am inside the getConditionaValue method
Inside LOOP3 value of i is 1
I am inside the getConditionaValue method
Inside LOOP3 value of i is 0
I am inside the getConditionaValue method