Java While Loop

Hello there, fellow coder! Today, we’re going to dive into the world of Java loops, specifically the while loop. Buckle up, because we’re about to embark on a looping journey!

Understanding the Java While Loop

In Java, a while loop is a control flow statement that allows code to be executed repeatedly based on a given condition. The while loop’s condition is checked before the loop is executed. So, if the condition is true, the loop will start executing.

while (condition) {
  // code block to be executed
}
Java

For example, if we want to print the numbers from 1 to 5, we can use a while loop like this:

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

In this code, as long as i is less than or equal to 5, the loop will print the value of i and then increment i by 1.

Flow Diagram of Java While Loop

Imagine a road with a checkpoint. Before you can go down the road, the checkpoint needs to be cleared. That’s how a while loop works! The condition is the checkpoint. If it’s true, you can go down the road (or run the code). If not, you can’t enter.

The flow of a Java while loop
The flow of a Java while loop

Java While Loop in Action: Examples

Let’s look at a simple example. We’ll use a while loop to print numbers from 1 to 5.

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

In this example, the loop will continue to print the value of i and increment it as long as i is less than or equal to 5.

Diving Deeper: Java Do-While Loop

The do-while loop is similar to the while loop, but with a key difference: the condition is checked after the loop is executed. This means that the do-while loop will execute at least once.

do {
  // code block to be executed
} while (condition);
Java

Let’s say we want to print the numbers from 1 to 5, but this time we’ll use a do-while loop:

int i = 1;
do {
  System.out.println(i);
  i++;
} while (i <= 5);
Java

Even if the condition i <= 5 becomes false, the loop will execute at least once because the condition is checked after the loop’s execution.

Java While Loop vs For Loop

While both while and for loops are used for iteration, they’re used in slightly different scenarios. Use a while loop when you’re not sure how many times you need to loop, and a for loop when you know the exact number of iterations.

Breaking the Loop: Using ‘break’ in Java While Loop

The break statement can be used to stop a while loop even if the while condition is true. It’s like an emergency stop button for your loop!

while (true) {
  // code block
  if (someCondition) {
    break;
  }
}
Java

For instance, let’s print numbers from 1 to 10, but we’ll stop (break) the loop when we reach 5:

int i = 1;
while (true) {
  if (i > 5) {
    break;
  }
  System.out.println(i);
  i++;
}
Java

In this code, the loop will break when i is greater than 5, even though the while condition is always true.

Continuing the Loop: Using ‘continue’ in Java While Loop

The continue statement skips the current iteration and jumps to the next one. It’s like saying, “This loop is boring, let’s go to the next one!”

while (condition) {
  // code block 1
  if (anotherCondition) {
    continue;
  }
  // code block 2
}
Java

Let’s print numbers from 1 to 10, but we’ll skip (continue) the loop when we reach 5:

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

In this code, the number 5 will not be printed because when i equals 5, the loop skips the current iteration and jumps to the next one.

Common Mistakes and Best Practices

One common mistake is creating an infinite while loop. Make sure your loop has a reachable stop condition. As for best practices, keep your loops clean and understandable. Don’t try to cram too much into a single loop.

Code Examples For Practice

Let’s look at a couple of complete code examples.

Example 1: A simple counter

int counter = 0;
while (counter < 5) {
  System.out.println("Counter: " + counter);
  counter++;
}
Java

In this example, we start with a counter set to 0. The while loop checks if the counter is less than 5. If it is, it prints the current value of the counter and then increments the counter by 1. This loop continues until the counter is no longer less than 5, at which point the loop ends.

How to Practice On SkillSeminary.com?

Visit Online Code Editor – Skill Seminary.

Select the Language to Java.

Copy the above code and paste the code after the line public static void main(String args[]){ and before next }.

Click the button “Run the Code”

How to run the code with a java while loop
How to run the Java code with a while loop

Example 2: Using break and continue

int number = 0;
while (number < 10) {
  number++;
  if (number == 5) {
    break;
  }
  if (number % 2 == 0) {
    continue;
  }
  System.out.println("Number: " + number);
}
Java

In this example, we start with a number set to 0. The while loop checks if the number is less than 10. If it is, it increments the number by 1. Then, it checks if the number is equal to 5. If it is, it breaks the loop, and no further code in the loop is executed. If the number is not 5, it checks if the number is even (i.e., if the remainder when the number is divided by 2 is 0). If the number is even, it continues to the next iteration of the loop, skipping the print statement. If the number is not even, it prints the number. This loop continues until the number is no longer less than 10 or until the number is equal to 5, at which point the loop ends.

Wrapping Up

And that’s a wrap on while loops in Java! They’re a powerful tool in your coding arsenal, so make sure to practice and understand them well.

Frequently Asked Questions (FAQ)

  • When should you use a while loop in Java?

    Use a while loop when you’re not sure how many times you need to loop.

  • How to keep getting input from user in Java?

    You can use a while loop with a Scanner object to keep getting input from the user.

  • How to take input from user in Java in loop?

    Use a Scanner object inside your loop to take user input on each iteration.

  • Can we use while and for loop together in Java?

    Yes, you can nest loops within each other.

  • How does a while loop work in Java?

    A while loop repeatedly executes a block of code as long as its condition is true.

  • What is the difference between a while loop and a do-while loop in Java?

    A while loop checks its condition before the loop is executed. A do-while loop checks its condition after the loop is executed, so it runs at least once.

  • How to break a while loop in Java?

    Use the break statement to exit a while loop prematurely.

  • How to continue a while loop in Java?

    Use the continue statement to skip to the next iteration of a while loop.

  • How to use a while loop for user input in Java?

    You can use a while loop with a Scanner object to get user input on each iteration.

  • What is the syntax of a while loop in Java?

    The syntax is while (condition) { // code }

That’s all, folks! Keep practicing, and happy coding!

Scroll to Top