While Loop in Java | Java While Loop Example
Learn to make your programs repeat actions over and over with while loops in Java! Just like a game loop, but smarter.
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
Best-suited Java courses for you
Learn Java with these high-rated online courses
Example: While Loop in Java
Let’s take an interesting example to understand and implement while loop in Java.
- 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!");
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}
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...");
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
- Keep track of how many times the loop happens using a special number called a “counter”.
- 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.
- Be careful not to make the loop go forever, otherwise it might crash the program.
- You can make the loop stop early or skip certain times with “break” or “continue” statements.
- If you know how many times the loop will happen, you can use for loop in java.
- Always double check the starting and ending values for the condition in the while loop, otherwise it may get stuck in an infinite loop.
- While debugging, add print statements inside the while loop so you can see what’s happening inside.
- Test your loops with different inputs and edge cases to ensure they work as expected.
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.
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!"); }}
- 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:
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