The definition of while loop is something like below and the code which is inside the curly braces {} executes until the conditional expression becomes false
Another example is if an external service or method is returning collections which you want to iterate and read the data and you don’t know how many elements are exist’s then you can use While loop
1 2 3 | while(condition) { // write code here } |
Example
In the below code if the number is less than 10 then the code executes within the while block, when condition becomes false then it will come out of the loop
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | package com.keysandstrokes.examples; public class WhileCondition { public static void main(String[] args) { int number = 0; while (number <= 10) { System.out.println("Number is " + number); number++; } } } |
Output
1 2 3 4 5 6 7 8 9 10 11 | Number is 0 Number is 1 Number is 2 Number is 3 Number is 4 Number is 5 Number is 6 Number is 7 Number is 8 Number is 9 Number is 10 |
Example 2
1 2 3 4 5 6 7 8 9 10 11 | ArrayList<String> users = new ArrayList<String>(); users.add("author1"); users.add("author2"); users.add("author3"); users.add("author4"); Iterator<String> usersIte = users.iterator(); while (usersIte.hasNext()) { String type = (String) usersIte.next(); System.out.println(type); } |
Output
1 2 3 4 | author1 author2 author3 author4 |