How To Use The While Loop In Java

Published Jul 02, 2017
How To Use The While Loop In Java

The While Loop:

We already went over how to write something to the Console.

System.out.println(“Hello, World!”);

Now what if we wanted to output “Hello, World!” to the console 100 times? We could type it out, which would increase our application file size substantially, or we could use a Loop:

int i = 0;
while(i < 100) {
System.out.println(“Hello, World!”);
i++;
}
System.out.println(“Completed Loop”);

A Loop is, as the name suggests, something that loops. It takes in a Boolean as an input, and if that Boolean is true, it executes whatever is between our curly brackets, then it will LOOP until the given Boolean will be false, at which point it will move on to the rest of the application. In the code above, we input a comparative operator(which returns a boolean):

while (i < 100) {

And if the operator returns true, it will execute what is between the curly brackets:

System.out.println(“Hello, World!”);
i++;

It will print “Hello,World!”, add 1 to i, and then check whether (i < 100) is true, and while it is true, it will repeat, until finally after “Hello,World!” has been printed 100 times, i will be equal to 100, and thus won’t be less than 100, and 

(i < 100) will return false, after which it will exit the Loop and execute the final line:

System.out.println(“Completed Loop”);

So if we wanted to essentially crash our program and print “Hello, World!” to the screen forever(at least until the Operating System doesn’t forcefully close the application) we could! Simply input true into the parentheses and the input will always be true, thus the loop will continue forever:

while(true) {
System.out.println(“Hello, World!”);
}

Discover and read more posts from Arseniy
get started
Enjoy this post?

Leave a like and comment for Arseniy

1
Be the first to share your opinion

Get curated posts in your inbox

Read more posts to become a better developer