Skip to content

Same or Different?

Can we use for and while loops to do the same thing?

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

While vs. For

We talked about the while loop and the for loop in the previous lessons.

They both have obvious differences but can also be used interchangeably.

Should you use them interchangeably? Probably not, but it's good to know how they can be.

It also allows us to see the differences between both types of iterating types.

Here's our first example, iterating 10 times:

Java
int j = 0;
while(j < 10) {
  System.out.println(j);
  j++;
}

for(int i = 0; i < 10; i++) {
  System.out.println(i);
}

These do the same thing. You can use either of them. However, here are where the differences start.

We can specify more conditions with the while loop, as it's not dependent on several loops.

We can also specify more conditions with the for loop, but its design doesn't promote this.

Here's the main rule to follow: If you know how many loops/iterations, use the for loop. Otherwise, use the while loop.

break

Let's talk about something else we can do with loops: break.

break is used to "break" out of a loop. Here is an example of using it in both while/for loops:

Java
int j = 0;

while(j < 10) {
  if(j == 5) {
    break;
  }
  j++;
}

for(int i = 0; i < 10; i++) {
  if(i == 5) {
    break;
  }
}

It allows us to break the loop, moving onto the next thing to execute.

continue

While break breaks the entire loop, continue is used to skip an iteration. This is helpful if you want your loop to go through all the values except one of them.

Java
int j = 0;

while(j < 10) {
  if(j == 5) {
    continue;
  }
  System.out.println(j);
  j++;
}

for(int i = 0; i < 10; i++) {
  if(i == 5) {
    continue;
  }
  System.out.println(i);
}