While Loop in Java | Java While Loop Example

While Loop in Java | Java While Loop Example

5 mins read762 Views Comment
Atul
Atul Harsha
Senior Manager Content
Updated on Jan 24, 2024 13:56 IST

Learn to make your programs repeat actions over and over with while loops in Java! Just like a game loop, but smarter.

2023_01_MicrosoftTeams-image-11.jpg

A while loop in Java is a conditional statement that lets you repeat a set of instructions as long as a certain condition is true. Think of it like a game of “while this is true, do this.” In Java, a while loop is a control flow statement that repeatedly executes a block of code as long as a given condition is true.

While Loop Syntax:

while (condition) {
    // code to be executed
}
  • condition is evaluated before each iteration of the loop
  • If condition is true, the code block inside the while loop will execute
  • The process repeats until condition is false
While loop in java – JAVA

Example: While Loop in Java

Let’s take an interesting example to understand and implement while loop in Java.

Super Mario Run now available for Android (update) - Polygon
  • Imagine you are playing a video game and you want to reach to the next level
  • But for this you need to collect enough coins to advance to the next level
  • Use a while loop to keep track of how many coins are collected
  • Loop continues until enough coins are collected to advance the level

NOTE: It is important to ensure the condition will eventually become false otherwise it will result in infinite loop.

Let’s try to implement the above scenario in Java


 
int coins = 0;
int coinsNeeded = 5; // Coins needed to buy a 1-up mushroom
while (coins < coinsNeeded) {
// Collect a coin, one step closer to that extra life
coins++;
// Additional game instructions like jumping on Goombas and hitting question blocks go here
}
System.out.println("Congratulations, you've collected enough coins to buy a 1-up mushroom! Keep collecting for extra lives!");
Copy code

Dry Run:

  • In the first iteration, the variable coins is 0 and less than coinsNeeded so the loop runs and variable coins increased by 1
  • In the second iteration, the variable coins is 1 and still less than coinsNeeded so the loop runs and variable coins increased by 1
  • The process keeps repeating in the similar manner until the variable coins becomes equal to 5.
  • The while loop condition becomes false and the loop stops.
  • And the final message is printed on the console.
Iteration coins coinsNeeded coins < coinsNeeded coins++
1 0 5 true 1
2 1 5 true 2
3 2 5 true 3
4 3 5 true 4
5 4 5 true 5
6 5 5 false  

Infinite While Loop in Java

An infinite while loop is a loop that never exits, and continues to execute indefinitely.

Here is an example of an infinite while loop in Java:


 
while (true) {
// Code inside the loop will execute indefinitely
}
Copy code

This while loop uses the constant boolean value true as its condition, which is always true, so the loop will never exit.

NOTE: It is very important to be careful while using infinite loops. As there is no mechanism in the loop to exit, the loop will run forever and will hang or crash your program.

How to deal with Infinite Loop in Java?

Now the question comes, how to deal with this? Let’s understand how to use a infinite loop in your program with an example:


 
int i = 0;
while (true) {
System.out.println("Iteration " + i);
i++;
if (i > 10) {
break; //this will break the loop once i is greater than 10
}
}
System.out.println("Exiting loop...");
Copy code

In this example, the while loop runs indefinitely, but it also keeps track of how many iterations have occurred using the i variable. If the value of i becomes greater than 10, the loop will exit and the program will continue running.

This way we are using the same while(true) approach, but adding a break statement to exit the loop after certain number of iteration.

For advanced readers, here’s an while loop java example you can follow to see how it is being used on a more realistic problem statement.

Tips and Tricks for using While Loop in Java

  1. Keep track of how many times the loop happens using a special number called a “counter”.
  2. Use a boolean variable to control the loop, rather than using the condition of the loop directly. This can make the code more readable and easier to modify later.
  3. Be careful not to make the loop go forever, otherwise it might crash the program.
  4. You can make the loop stop early or skip certain times with “break” or “continue” statements.
  5. If you know how many times the loop will happen, you can use for loop in java.
  6. Always double check the starting and ending values for the condition in the while loop, otherwise it may get stuck in an infinite loop.
  7. While debugging, add print statements inside the while loop so you can see what’s happening inside.
  8. Test your loops with different inputs and edge cases to ensure they work as expected.

Read More:

Mastering For Loops in Java: A Comprehensive Guide
Mastering For Loops in Java: A Comprehensive Guide
Learn how to use for loops in Java to control the flow of your programs and automate repetitive tasks. Understand the basics of for loops, nested for loops, for-each loops...read more
For each loop in Java
For each loop in Java
This blog will help you learn the concepts of for each loop in Java. You can use it to iterate through the elements of an array or collection without using...read more
 

 

Scenario: Automating Email Marketing – Streamlining Campaigns and Tracking Success

Problem Statement:

A marketing team wants to send a promotional email to a large list of customers with an automatic program, and they want to keep track of the number of emails sent, number of emails bounced, and number of emails opened.

Email Marketing Images - Free Download on Freepik

Solution:


 
import java.util.List; // import the List class to use Lists in the program
public class EmailMarketing {
public static void main(String[] args) {
List<String> customerEmails = getCustomerEmails(); // grab a list of email of all the lonely people from the database
int emailsSent = 0; // number of emails sent to people who don't care
int emailsBounced = 0; // number of emails sent to ghosts
int emailsOpened = 0; // number of emails read by people who are still alive
System.out.println("Starting the spamming process...");
int index = 0;
while (index < customerEmails.size()) { // loop through all customer emails in the list
String email = customerEmails.get(index); // get the email of the current customer in the loop
try {
sendEmail(email); // send unwanted emails to inboxes
System.out.println("Email sent to " + email + ". Hopefully they'll be excited to hear from us!");
emailsSent++;
}
catch (Exception e) {
System.out.println("Email bounced when sending to " + email + ". Ghost mailbox probably.");
emailsBounced++; // sending emails to ghosts
}
index++; // increment the index to move to the next customer email in the list
// check if the email was opened by someone who is still alive
if (wasEmailOpened(email)) {
System.out.println("Someone actually opened our email at " + email + "!!");
emailsOpened++;
}
}
// print the number of emails sent, bounced, and opened
System.out.println("Emails Sent: " + emailsSent);
System.out.println("Emails Bounced: " + emailsBounced);
System.out.println("Emails Opened: " + emailsOpened);
System.out.println("Spamming process complete. Time to wait for the cash to roll in!");
}
}
Copy code
  • A marketing team wants to send promotional emails to a large list of customers.
  • They want to keep track of the number of emails sent, bounced, and opened.
  • A while loop is used to iterate through the list of customer emails, sending one email at a time.
  • The loop also keeps track of how many emails have been sent, bounced, and opened.
  • Once complete, it prints out the final count of emails sent, bounced, and opened for the team to track the campaign performance
  • This allows the program to handle a high volume of emails without manual intervention and also provide the result of the campaign.

Note: This is just a harmless example of using a while loop with a list of emails, to help with understanding the code. Not for actual spamming, which is illegal and not good practice.

Conclusion

In conclusion, while loops in Java are a powerful tool for repeating a set of instructions as long as a certain condition is met. It is important to keep in mind that while they can be useful in many situations, they must be used responsibly.

And as always, if you found this information helpful, don’t forget to give it a like, share it with your friends, and subscribe to stay updated on more Java tips and tricks.

Read More:

Swapping of Two Numbers in Java
Swapping of Two Numbers in Java
Get an introduction to swapping the values of two numbers in Java using different methods. Compare the use of a temporary variable, arithmetic operators, and bitwise operators for swapping numbers.
How to Check Leap Year in Java?
How to Check Leap Year in Java?
In this blog, you will learn how to check leap year in Java. A leap year is a year that is divisible by 4 and 400 but not by 100....read more
Switch Case in Java with Examples
Switch Case in Java with Examples
Switch statements in Java enable execution of different code blocks based on the value of an expression. They provide an alternative to multiple if-else statements and can be used when...read more
Armstrong Number in Java using Different Methods
Armstrong Number in Java using Different Methods
Learn to check if a number is an Armstrong number in Java using while loop or recursion. Understand the mathematical definition and see code examples for easy implementation
Check Palindrome in Java Using Different Methods
Check Palindrome in Java Using Different Methods
Discover various methods for checking if a string is a palindrome in Java. Use recursion and string manipulation to efficiently determine if a string is a palindrome, ignoring spaces, punctuation,...read more
Fibonacci Series in Java [Case-Study Based]
Fibonacci Series in Java [Case-Study Based]
The Fibonacci series is a sequence of numbers in which each number is the sum of the two preceding ones, usually starting with 0 and 1. In Java, the Fibonacci...read more
About the Author
author-image
Atul Harsha
Senior Manager Content

Experienced AI and Machine Learning content creator with a passion for using data to solve real-world challenges. I specialize in Python, SQL, NLP, and Data Visualization. My goal is to make data science engaging an... Read Full Bio