0% found this document useful (0 votes)
31 views9 pages

Haha 5

Uploaded by

raroy67751
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views9 pages

Haha 5

Uploaded by

raroy67751
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 9

Skip to content

geeksforgeeks
Courses 90% Refund
Tutorials
Java
Practice
Contests

Sign In

Java Arrays
Java Strings
Java OOPs
Java Collection
Java 8 Tutorial
Java Multithreading
Java Exception Handling
Java Programs
Java Project
Java Collections Interview
Java Interview Questions
Java MCQs
Spring
Spring MVC
Spring Boot
Hibernate

Content Improvement Event


Share Your Experiences
Java Tutorial
Overview of Java
Basics of Java
Input/Output in Java
Flow Control in Java
Decision Making in Java (if, if-else, switch, break, continue, jump)
Java if statement with Examples
Java if-else
Java if-else-if ladder with Examples
Loops in Java
For Loop in Java
Java while loop with Examples
Java do-while loop with Examples
For-each loop in Java
Continue Statement in Java
Break statement in Java
Usage of Break keyword in Java
return keyword in Java
Operators in Java
Strings in Java
Arrays in Java
OOPS in Java
Inheritance in Java
Abstraction in Java
Encapsulation in Java
Polymorphism in Java
Constructors in Java
Methods in Java
Interfaces in Java
Wrapper Classes in Java
Keywords in Java
Access Modifiers in Java
Memory Allocation in Java
Classes of Java
Packages in Java
Java Collection Tutorial
Exception Handling in Java
Multithreading in Java
Synchronization in Java
File Handling in Java
Java Regex
Java IO
Java Networking
JDBC - Java Database Connectivity
Java 8 Features - Complete Tutorial
Java Backend DevelopmentCourse
Java while loop with Examples
Last Updated : 13 Dec, 2023
Java while loop is a control flow statement that allows code to be executed
repeatedly based on a given Boolean condition. The while loop can be thought of as
a repeating if statement. While loop in Java comes into use when we need to
repeatedly execute a block of statements. The while loop is considered as a
repeating if statement. If the number of iterations is not fixed, it is recommended
to use the while loop.

while loop in Java

Syntax:

while (test_expression)
{
// statements

update_expression;
}
Note: If we do not provide the curly braces ‘{‘ and ‘}’ after while( condition )
then by default while statement will consider the immediate one statement to be
inside its block.

while (test_expression)
// single statement in while only

Parts of Java While Loop


The various parts of the While loop are:

1. Test Expression: In this expression, we have to test the condition. If the


condition evaluates to true then we will execute the body of the loop and go to
update expression. Otherwise, we will exit from the while loop.

Example:

i <= 10
2. Update Expression: After executing the loop body, this expression
increments/decrements the loop variable by some value.

Example:

i++;
How Does a While loop execute?
Control falls into the while loop.
The flow jumps to Condition
Condition is tested.
If Condition yields true, the flow goes into the Body.
If Condition yields false, the flow goes outside the loop
The statements inside the body of the loop get executed.
Updation takes place.
Control flows back to Step 2.
The while loop has ended and the flow has gone outside.
Flowchart For while loop (Control Flow):
Flow chart while loop (for Control Flow

Examples of Java while loop


Example 1: This program will try to print “Hello World” 5 times.

// Java program to illustrate while loop.

class whileLoopDemo {
public static void main(String args[])
{
// initialization expression
int i = 1;

// test expression
while (i < 6) {
System.out.println("Hello World");

// update expression
i++;
}
}
}
Output
Hello World
Hello World
Hello World
Hello World
Hello World

Complexity of the above method:


Time Complexity: O(1)
Auxiliary Space : O(1)

Dry-Running Example 1: The program will execute in the following manner.

1. Program starts.
2. i is initialized with value 1.
3. Condition is checked. 1 < 6 yields true.
3.a) "Hello World" gets printed 1st time.
3.b) Updation is done. Now i = 2.
4. Condition is checked. 2 < 6 yields true.
4.a) "Hello World" gets printed 2nd time.
4.b) Updation is done. Now i = 3.
5. Condition is checked. 3 < 6 yields true.
5.a) "Hello World" gets printed 3rd time
5.b) Updation is done. Now i = 4.
6. Condition is checked. 4 < 6 yields true.
6.a) "Hello World" gets printed 4th time
6.b) Updation is done. Now i = 5.
7. Condition is checked. 5 < 6 yields true.
7.a) "Hello World" gets printed 5th time
7.b) Updation is done. Now i = 6.
8. Condition is checked. 6 < 6 yields false.
9. Flow goes outside the loop. Program terminates.

Example 2: This program will find the summation of numbers from 1 to 10.

// Java program to illustrate while loop

class whileLoopDemo {
public static void main(String args[])
{
int x = 1, sum = 0;

// Exit when x becomes greater than 4


while (x <= 10) {
// summing up x
sum = sum + x;

// Increment the value of x for


// next iteration
x++;
}
System.out.println("Summation: " + sum);
}
}
Output
Summation: 55

Complexity of the above method


Time Complexity: O(1)
Auxiliary Space : O(1)

Video Referal for Java while Loop


Related Articles:

Loops in Java
Java For loop with Examples
Java do-while loop with Examples
Difference between for and while loop in C, C++, Java
Difference between while and do-while loop in C, C++, Java

Three 90 Challenge is back on popular demand! After processing refunds worth INR
1CR+, we are back with the offer if you missed it the first time. Get 90% course
fee refund in 90 days. Avail now!
Want to be a master in Backend Development with Java for building robust and
scalable applications? Enroll in Java Backend and Development Live Course by
GeeksforGeeks to get your hands dirty with Backend Programming. Master the key Java
concepts, server-side programming, database integration, and more through hands-on
experiences and live projects. Are you new to Backend development or want to be a
Java Pro? This course equips you with all you need for building high-performance,
heavy-loaded backend systems in Java. Ready to take your Java Backend skills to the
next level? Enroll now and take your development career to sky highs.
C

Chinmoy Lenka

89
Previous Article
For Loop in Java
Next Article
Java do-while loop with Examples
Read More
Down Arrow
Similar Reads
Difference between while and do-while loop in C, C++, Java
while loop: A while loop is a control flow statement that allows code to be
executed repeatedly based on a given Boolean condition. The while loop can be
thought of as a repeating if statement. Syntax : while (boolean condition){ loop
statements...}Flowchart: Example: [GFGTABS] C++ #include &lt;iostream&gt; using
namespace std; int main() { int i =
2 min read
Java do-while loop with Examples
Loops in Java come into use when we need to repeatedly execute a block of
statements. Java do-while loop is an Exit control loop. Therefore, unlike for or
while loop, a do-while check for the condition after executing the statements of
the loop body. Syntax: do { // Loop Body Update_expression } // Condition check
while (test_expression); Note: The
5 min read
While loop with Compile time constants
While loop is a control flow statement that allows code to be executed repeatedly
based on a given Boolean condition. The while loop can be thought of as a repeating
if statement. It is mostly used in situations where the exact number of iterations
beforehand. Below is the image to illustrate the while loop: Syntax:
while(test_expression){ // state
6 min read
Difference Between for loop and Enhanced for loop in Java
Java for-loop is a control flow statement that iterates a part of the program
multiple times. For-loop is the most commonly used loop in java. If we know the
number of iteration in advance then for-loop is the best choice. Syntax:
for( initializationsection ; conditional check ; increment/decrement section) { //
Code to be executed } Curly braces i
5 min read
How to Avoid TLE While Coding in Java?
Avoiding Time Limit Exceeded(TLE) is one of the most important aspects that we need
to take care of while doing competitive coding as well as while answering questions
on DSA during a technical PI. In this context, one commonly asked question across
all coding platforms is sorting or problems that involve sorting. The following
code is something I
5 min read
ConcurrentModificationException while using Iterator in Java
ConcurrentModificationException has thrown by methods that have detected concurrent
modification of an object when such modification is not permissible. If a thread
modifies a collection directly while it is iterating over the collection with a
fail-fast iterator, the iterator will throw this ConcurrentModificationException.
Here we will be underst
3 min read
Java - Parameters Responsible for Difference in Outputs while Running on Local IDE
vs Online IDE
The concept involved in the difference in output between running a Java program on
a local IDE and an online IDE is the environment in which the program is being run.
The specific version of Java, the settings and configurations of the IDE, and the
instructions in the program can all affect the output of the program. To understand
the differences i
4 min read
Remove an Entry using key from HashMap while Iterating over it
Given a HashMap and a key in Java, the task is to remove an entry from this HashMap
using the key, while iterating over it. Examples: Input: HashMap: {1=Geeks,
2=ForGeeks, 3=GeeksForGeeks}, key = 2 Output: {1=Geeks, 3=GeeksForGeeks} Input:
HashMap: {1=G, 2=e, 3=e, 4=k, 5=s}, key = 3 Output: {1=G, 2=e, 4=k, 5=s} Using Java
7 and before: Get the Hash
3 min read
Remove an Entry using value from HashMap while Iterating over it
Given a HashMap and a value in Java, the task is to remove an entry from this
HashMap using the value, while iterating over it. Examples: Input: HashMap:
{1=Geeks, 2=ForGeeks, 3=GeeksForGeeks}, value = "ForGeeks" Output: {1=Geeks,
3=GeeksForGeeks} Input: HashMap: {1=G, 2=e, 3=e, 4=k, 5=s}, value = k Output: {1=G,
2=e, 3=e, 5=s} Using Java 7 and bef
3 min read
Hello World Program : First program while learning Programming
In this article, I'll show you how to create your first Hello World computer
program in various languages. Along with the program, comments are provided to help
you better understand the terms and keywords used in theLearning program.
Programming can be simplified as follows: Write the program in a text editor and
save it with the correct extension
6 min read
Article Tags :
Java
Practice Tags :
Java
three90RightbarBannerImg
course-img
215k+ interested Geeks
Master Java Programming - Complete Beginner to Advanced
Explore
course-img
214k+ interested Geeks
JAVA Backend Development - Live
Explore
course-img
30k+ interested Geeks
Manual to Automation Testing: A QA Engineer's Guide
Explore
geeksforgeeks-footer-logo
Corporate & Communications Address:- A-143, 9th Floor, Sovereign Corporate Tower,
Sector- 136, Noida, Uttar Pradesh (201305) | Registered Address:- K 061, Tower K,
Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh,
201305
GFG App on Play Store
GFG App on App Store
Company
About Us
Legal
Careers
In Media
Contact Us
Advertise with us
GFG Corporate Solution
Placement Training Program
Explore
Job-A-Thon Hiring Challenge
Hack-A-Thon
GfG Weekly Contest
Offline Classes (Delhi/NCR)
DSA in JAVA/C++
Master System Design
Master CP
GeeksforGeeks Videos
Geeks Community
Languages
Python
Java
C++
PHP
GoLang
SQL
R Language
Android Tutorial
DSA
Data Structures
Algorithms
DSA for Beginners
Basic DSA Problems
DSA Roadmap
DSA Interview Questions
Competitive Programming
Data Science & ML
Data Science With Python
Data Science For Beginner
Machine Learning Tutorial
ML Maths
Data Visualisation Tutorial
Pandas Tutorial
NumPy Tutorial
NLP Tutorial
Deep Learning Tutorial
Web Technologies
HTML
CSS
JavaScript
TypeScript
ReactJS
NextJS
NodeJs
Bootstrap
Tailwind CSS
Python Tutorial
Python Programming Examples
Django Tutorial
Python Projects
Python Tkinter
Web Scraping
OpenCV Tutorial
Python Interview Question
Computer Science
GATE CS Notes
Operating Systems
Computer Network
Database Management System
Software Engineering
Digital Logic Design
Engineering Maths
DevOps
Git
AWS
Docker
Kubernetes
Azure
GCP
DevOps Roadmap
System Design
High Level Design
Low Level Design
UML Diagrams
Interview Guide
Design Patterns
OOAD
System Design Bootcamp
Interview Questions
School Subjects
Mathematics
Physics
Chemistry
Biology
Social Science
English Grammar
Commerce
Accountancy
Business Studies
Economics
Management
HR Management
Finance
Income Tax
Databases
SQL
MYSQL
PostgreSQL
PL/SQL
MongoDB
Preparation Corner
Company-Wise Recruitment Process
Resume Templates
Aptitude Preparation
Puzzles
Company-Wise Preparation
Companies
Colleges
Competitive Exams
JEE Advanced
UGC NET
UPSC
SSC CGL
SBI PO
SBI Clerk
IBPS PO
IBPS Clerk
More Tutorials
Software Development
Software Testing
Product Management
Project Management
Linux
Excel
All Cheat Sheets
Recent Articles
Free Online Tools
Typing Test
Image Editor
Code Formatters
Code Converters
Currency Converter
Random Number Generator
Random Password Generator
Write & Earn
Write an Article
Improve an Article
Pick Topics to Write
Share your Experiences
Internships
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By
using our site, you acknowledge that you have read and understood our Cookie Policy
& Privacy Policy
Got It !
Lightbox

You might also like