Java/J2EE and SOA (349 Blogs) Become a Certified Professional
AWS Global Infrastructure

Programming & Frameworks

Topics Covered
  • C Programming and Data Structures (16 Blogs)
  • Comprehensive Java Course (4 Blogs)
  • Java/J2EE and SOA (346 Blogs)
  • Spring Framework (8 Blogs)
SEE MORE

What is a While Loop in Java and how to use it?

Last updated on Aug 28,2024 17.4K Views

2 / 5 Blog from Control Statements

Java language offers you to work with several loops. Loops are basically used to execute a set of statements repeatedly until a particular condition is satisfied. Here, I will tell you about the ‘while’ loop in Java. The topics included in this article are mentioned below:

Let’s begin!

What is a while loop in Java?

The Java while loop is used to iterate a part of the program again and again. If the number of iteration is not fixed, then you can use while loop.

A pictorial representation of how a while loop works:

While Loop in Java - EdurekaIn the above diagram, when the execution begins and the condition returns false, then the control jumps out to the next statement after the while loop. On the other hand, if the condition returns true then the statement inside the while loop is executed.

Moving on with this article on While Loop in Java, Let’s have a look at the syntax:

Syntax:

while (condition) {

  // code block to be executed

}

Now that I have shown you the syntax, here is an example:

Practical Implementation:

class Example {
    public static void main(String args[]){
         int i=10;
         while(i>1){
              System.out.println(i);
              i--;
         }
    }
}

Output:

10
9
8
7
6
5
4
3
2

Next, let’s take a look at another example:

Another example of While Loop in Java:

// Java While Loop example

package Loops;

import java.util.Scanner;

public class WhileLoop {
	private static Scanner sc;
	
	public static void main(String[] args) {
		int number, sum = 0;
		sc = new Scanner(System.in);	
		
		System.out.println("n Please Enter any integer Value below 10: ");
		number = sc.nextInt();
		
		while (number <= 10)  {
			sum = sum + number;
			number++;
		}
		System.out.format(" Sum of the Numbers From the While  Loop is: %d ", sum);
	}
}

 

Output:

Please Enter any integer Value below 10: 7
Sum of the Numbers From the While  Loop is: 34

Above illustrated example is a bit complex as compared to the previous one. Let me explain it step by step.

In this Java while loop example, the machine would ask the user to enter any integer value below 10. Next, the While loop and the Condition inside the While loop will assure that the given number is less than or equal to 10.

Now, User Entered value = 7 and I have initialized the sum = 0

This is how the iteration would work: (concentrate on the while loop written in the code)

Related Learning: Core Java Interview Questions

First Iteration:

sum = sum + number
sum = 0 + 7 ==> 7
Now, the number will be incremented by 1 (number ++)

Second Iteration

Now in the first iteration the values of both Number and sum has changed as: Number = 8 and sum = 7
sum = sum + number
sum = 7 + 8 ==> 15
Again, the number will be incremented by 1 (number ++)

Third Iteration

Now, in the Second Iteration, the values of both Number and sum has changed as: Number = 9 and sum = 15
sum = sum + number
sum = 15 + 9 ==> 24
Following the same pattern, the number will be incremented by 1 (number ++) again.

Fourth Iteration

In the third Iteration of the Java while loop, the values of both Number and sum has changed as: Number = 10 and sum = 24
sum = sum + number
sum = 24 + 10 ==> 34

Finally, the number will be incremented by 1 (number ++) for the last time.

Here, Number = 11. So, the condition present in the while loop fails.

In the end, System.out.format statement will print the output as you can see above!

Moving further,

One thing that you need to keep in mind is that you should use increment or decrement statement inside while loop so that the loop variable gets changed on each iteration so that at some point, the condition returns false. This way you can end the execution of the while loop. Else, the loop would execute indefinitely. In such cases, where the loop executes indefinitely, you’ll encounter a concept of the infinite while loop in Java, which is our next topic of discussion!

Infinite while loop in Java

The moment you pass ‘true’ in the while loop, the infinite while loop will be initiated.

Syntax:

while (true){
    statement(s);
}

Practical Demonstration

Let me show you an example of Infinite While Loop in Java:

class Example {
    public static void main(String args[]){
         int i=10;
         while(i>1)
         {
             System.out.println(i);
              i++;
         }
    }
}

 

It’s an infinite while loop, hence it won’t end. This is because the condition in the code says i>1 which would always be true as we are incrementing the value of i inside the while loop.

With this, I have reached towards the end of this blog. I really hope the above-shared content added value to your Java knowledge. Let us keep exploring Java world together. Stay tuned!

Check out the Java Online Training by Edureka, a trusted online learning company with a network of more than 250,000 satisfied learners spread across the globe. Edureka’s Java J2EE and SOA training and certification course is designed for students and professionals who want to be a Java Developer. The course is designed to give you a head start into Java programming and train you for both core and advanced Java concepts along with various Java frameworks like Hibernate & Spring.

Got a question for us? Please mention it in the comments section of this ‘’While loop in Java” blog and we will get back to you as soon as possible.

Upcoming Batches For Java Course Online
Course NameDateDetails
Java Course Online

Class Starts on 28th September,2024

28th September

SAT&SUN (Weekend Batch)
View Details
Comments
0 Comments

Join the discussion

Browse Categories

webinar REGISTER FOR FREE WEBINAR
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP

Subscribe to our Newsletter, and get personalized recommendations.

image not found!
image not found!

What is a While Loop in Java and how to use it?

edureka.co