What does the while loop do? Easy explanation

Aylin Ibrahimli
GitStacks

--

First of all, let’s discuss what are loops in Java and how many of them are there. There are 3 types of loops in Java and they are the for loop, the while loop, and the do-while loop. Today we are going to discuss only one of them which is the while loop in Java. The other two loops will be discussed in my next articles.

Explanation

Probably you’re wondering what does while loop do. Well, here is the answer to your question. While loop executes a block of code as long as its condition remains true. It’s kind of like an if statement but it will continue that block of code continuously as long as its condition remains true. F.E: if the program asks you to type your name but you aren’t doing that then it will keep on typing you enter your name. Let’s do something like that in Eclipse IDE

Practice Time!

So let’s create a scanner,(If you don’t know what is a scanner or a String variable then you can always read my previous articles about java)and a new String variable for the name and set it equal to a pair of quotes for now:

Now, it’s time to create the while loop. Type:

while(name.isBlank()) {

System.out.println(“Please enter your name:”);

name = scanner.nextLine();

}

As you can see the while loop as I said earlier looks like an if statement where inside the brackets we said to the computer that if the user didn’t type anything, then it would keep typing you to enter your name

--

--