Skip to content

While Loops

  • Lesson
  • 2 min read
  • 2 of 4 in this chapter

The most basic loop

To get iteration kicked off, we are going to start with the while loop.

The while loop will continue forever, until the condition we give it becomes false.

So for example, we can have a while loop run until number becomes 100. In fact, let's try that out:

Java
int number = 1;
while(number <= 100) {
System.out.println(number);
number++;
}

If you run this, you will print 100 lines, each one greater by one than the last.

It will stop at 100 since the condition says that number must be less than 100 to continue.

And that's basically it.

Stop on input

Let's do something a bit more complex. We will let the loop run until it reaches 10 OR if we tell it not to.

Java
Scanner input = new Scanner(System.in);
int number = 1;
boolean stop = false;

while(!stop && number <= 10) {
  System.out.println("Loop #" + (number));

  System.out.println("Do you want to stop? (y/n)");
  String choice = input.nextLine();
  if(choice.equals("y")) {
    stop = true;
  } else {
    number++;
  }
}
System.out.println("Loop stopped after " + number);

Remember that .equals is the same as ==, except it's exclusive for String (when it comes to primitive types)