While Loop in Java
Loops in programming languages allow code to be repeated multiple times until a condition is met to stop repeating the action. They can be helpful in reducing the number of lines of code or the number of times the action should be repeated can change depending on different conditions. In this post, we'll cover how the while
loop works in Java.
While Loop Concepts
There are four parts to loops in programming languages: initialization, terminating condition, loop body, and update. The initialization is used to create a variable that will be used to compare with the terminating condition. The terminating condition is an expression that determines whether the loop should continue on or exit. The loop body is the code that gets executed if the loop is allowed to continue on. The update part is how we update the variable to effect the terminating condition, which determines whether to loop again or not.
Consider an example of printing out the world "Hello" three times:
int number = 0;while (number < 3) {System.out.println("Hello");number++;}
Here we initialize the number with a value of 0
. Since 0 < 3
is true
, the body of the while loop gets executed and "Hello" gets printed. Then the number is incremented by 1
. When we get to the comparison 3 < 3
, it evaluates to false
and the body of the while loop does not get executed and the loop exits.
This is not the only way to implement this program. We could also decrement the variable instead. Whichever is more readable and easier to understand is up to you. Alternatively we could write:
int number = 3;while (number > 0) {System.out.println("Hello");number--;}
While Loop Use Cases
While loops are especially useful when we do not know how many times the loop should execute. For example, we may want to keep repeating an action until the user wants to quit the application.
Scanner scanner = new Scanner(System.in);System.out.println("Enter 'q' to quit or any other button to continue:");String input = scanner.nextLine();while (input != "q") {System.out.println("Enter 'q' to quit or any other button to continue:");input = scanner.nextLine();}
In this case, there is no specific number of times the loop body should execute. For example, they could enter 'q' right away or enter it 20 entries later. Because of this uncertainty, the while
loop is useful.
Conclusion
Loops are useful whenever we need to repeat an action. In this post, we learned about the while
loop and its use cases.