Java While Loop

Last updated: January 16, 2024

java assignment while loop

We've opened a new role Backend Java/Spring Team Lead with Integration Experience . Part-time and entirely remote, of course.

An in-depth piece exploring building a modular event-driven microservices architecture, using Spring and Orkes Conductor for orchestration:

>> Event-Driven Microservices With Orkes Conductor

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only , so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server's performance, with most of the profiling work done separately - so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server , hit the record button, and you'll have results within minutes:

>> Try out the Profiler

Microsoft JDConf 2024 conference is getting closer, on March 27th and 28th. Simply put, it's a free virtual event to learn about the newest developments in Java, Cloud, and AI.

Josh Long and Mark Heckler are kicking things off in the keynote, so it's definitely going to be both highly useful and quite practical.

This year’s theme is focused on developer productivity and how these technologies transform how we work, build, integrate, and modernize applications.

For the full conference agenda and speaker lineup, you can explore JDConf.com:

>> RSVP Now

Accelerate Your Jakarta EE Development with Payara Server!

With best-in-class guides and documentation, Payara essentially simplifies deployment to diverse infrastructures.

Beyond that, it provides intelligent insights and actions to optimize Jakarta EE applications.

The goal is to apply an opinionated approach to get to what's essential for mission-critical applications - really solid scalability, availability, security, and long-term support:

>> Download and Explore the Guide (to learn more)

Working on getting your persistence layer right with Spring?

Explore the eBook

Do JSON right with Jackson

Download the E-book

Get the most out of the Apache HTTP Client

Get Started with Apache Maven:

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> REST With Spring (new)

Get started with Spring and Spring Boot, through the reference Learn Spring course:

>> LEARN SPRING

Building a REST API with Spring?

The AI Assistant to boost Boost your productivity writing unit tests - Machinet AI .

AI is all the rage these days, but for very good reason. The highly practical coding companion, you'll get the power of AI-assisted coding and automated unit test generation . Machinet's Unit Test AI Agent utilizes your own project context to create meaningful unit tests that intelligently aligns with the behavior of the code. And, the AI Chat crafts code and fixes errors with ease, like a helpful sidekick.

Simplify Your Coding Journey with Machinet AI :

>> Install Machinet AI in your IntelliJ

Get non-trivial analysis (and trivial, too!) suggested right inside your IDE or Git platform so you can code smart, create more value, and stay confident when you push.

Get CodiumAI for free and become part of a community of over 280,000 developers who are already experiencing improved and quicker coding.

Write code that works the way you meant it to:

>> CodiumAI. Meaningful Code Tests for Busy Devs

Looking for the ideal Linux distro for running modern Spring apps in the cloud?

Meet Alpaquita Linux : lightweight, secure, and powerful enough to handle heavy workloads.

This distro is specifically designed for running Java apps . It builds upon Alpine and features significant enhancements to excel in high-density container environments while meeting enterprise-grade security standards.

Specifically, the container image size is ~30% smaller than standard options, and it consumes up to 30% less RAM:

>> Try Alpaquita Containers now.

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth , to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project .

You can explore the course here:

>> Learn Spring Security

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot .

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Just published a deep dive into building a relevance-focused search with MongoDB. More or less out of the box:

>> MongoDB Atlas Search

Creating PDFs is actually surprisingly hard. When we first tried, none of the existing PDF libraries met our needs. So we made DocRaptor for ourselves and later launched it as one of the first HTML-to-PDF APIs.

We think DocRaptor is the fastest and most scalable way to make PDFs , especially high-quality or complex PDFs. And as developers ourselves, we love good documentation, no-account trial keys, and an easy setup process.

>> Try DocRaptor's HTML-to-PDF Java Client (No Signup Required)

Get started with Spring and Spring Boot, through the Learn Spring course:

1. overview.

In this article, we’ll look at a core aspect of the Java language – executing a statement or a group of statements repeatedly using a while loop.

2. While Loop

The while loop is Java’s most fundamental loop statement. It repeats a statement or a block of statements while its controlling Boolean-expression is true.

The syntax of the while loop is:

The loop’s Boolean-expression is evaluated before the first iteration of the loop – which means that if the condition is evaluated to false, the loop might not run even once.

Let’s have a look at a simple example:

3. Conclusion

In this quick tutorial, we explored Java’s while loop.

As always, examples can be found over on GitHub .

Can Jakarta EE be used to develop microservices? The answer is a resounding ‘yes’!

>> Demystifying Microservices for Jakarta EE & Java EE Developers

Slow MySQL query performance is all too common. Of course it is.

The Jet Profiler was built entirely for MySQL , so it's fine-tuned for it and does advanced everything with relaly minimal impact and no server changes.

Explore the secure, reliable, and high-performance Test Execution Cloud built for scale. Right in your IDE:

Basically, write code that works the way you meant it to.

AI is all the rage these days, but for very good reason. The highly practical coding companion, you'll get the power of AI-assisted coding and automated unit test generation . Machinet's Unit Test AI Agent utilizes your own project context to create meaningful unit tests that intelligently aligns with the behavior of the code.

Build your API with SPRING - book cover

Java Tutorial

Java methods, java classes, java file handling, java how to, java reference, java examples, java while loop.

Loops can execute a block of code as long as a specified condition is reached.

Loops are handy because they save time, reduce errors, and they make code more readable.

The while loop loops through a block of code as long as a specified condition is true :

In the example below, the code in the loop will run, over and over again, as long as a variable (i) is less than 5:

Try it Yourself »

Note: Do not forget to increase the variable used in the condition, otherwise the loop will never end!

Advertisement

The Do/While Loop

The do/while loop is a variant of the while loop. This loop will execute the code block once, before checking if the condition is true, then it will repeat the loop as long as the condition is true.

The example below uses a do/while loop. The loop will always be executed at least once, even if the condition is false, because the code block is executed before the condition is tested:

Do not forget to increase the variable used in the condition, otherwise the loop will never end!

Test Yourself With Exercises

Print i as long as i is less than 6.

Start the Exercise

Get Certified

COLOR PICKER

colorpicker

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

[email protected]

Top Tutorials

Top references, top examples, get certified.

The Java Tutorials have been written for JDK 8. Examples and practices described in this page don't take advantage of improvements introduced in later releases and might use technology no longer available. See Java Language Changes for a summary of updated language features in Java SE 9 and subsequent releases. See JDK Release Notes for information about new features, enhancements, and removed or deprecated options for all JDK releases.

The while and do-while Statements

The while statement continually executes a block of statements while a particular condition is true . Its syntax can be expressed as:

The while statement evaluates expression , which must return a boolean value. If the expression evaluates to true , the while statement executes the statement (s) in the while block. The while statement continues testing the expression and executing its block until the expression evaluates to false . Using the while statement to print the values from 1 through 10 can be accomplished as in the following WhileDemo program:

You can implement an infinite loop using the while statement as follows:

The Java programming language also provides a do-while statement, which can be expressed as follows:

The difference between do-while and while is that do-while evaluates its expression at the bottom of the loop instead of the top. Therefore, the statements within the do block are always executed at least once, as shown in the following DoWhileDemo program:

About Oracle | Contact Us | Legal Notices | Terms of Use | Your Privacy Rights

Copyright © 1995, 2022 Oracle and/or its affiliates. All rights reserved.

  • C Program : Remove Vowels from A String | 2 Ways
  • C Program : Remove All Characters in String Except Alphabets
  • C Program : Sorting a String in Alphabetical Order – 2 Ways
  • C Program To Check If Vowel Or Consonant | 4 Simple Ways
  • C Program To Print Number Of Days In A Month | Java Tutoring
  • C Program To Check Whether A Number Is Even Or Odd | C Programs
  • C Program To Find Reverse Of An Array – C Programs
  • C Program To Count The Total Number Of Notes In A Amount | C Programs
  • C Program To Check A Number Is Negative, Positive Or Zero | C Programs
  • C Program To Input Any Alphabet And Check Whether It Is Vowel Or Consonant
  • C Program Inverted Pyramid Star Pattern | 4 Ways – C Programs
  • C Program To Check Whether A Character Is Alphabet or Not
  • C Program To Check Character Is Uppercase or Lowercase | C Programs
  • C Program To Check If Alphabet, Digit or Special Character | C Programs
  • C Program To Find Maximum Between Three Numbers | C Programs
  • C Program To Check Whether A Year Is Leap Year Or Not | C Programs
  • C Program Area Of Triangle | C Programs
  • C Program To Check If Triangle Is Valid Or Not | C Programs
  • C Program Find Circumference Of A Circle | 3 Ways
  • C Program To Calculate Profit or Loss In 2 Ways | C Programs
  • C Program Area Of Rectangle | C Programs
  • X Star Pattern C Program 3 Simple Ways | C Star Patterns
  • C Program Hollow Diamond Star Pattern | C Programs
  • C Program To Check Number Is Divisible By 5 and 11 or Not | C Programs
  • Mirrored Rhombus Star Pattern Program In c | Patterns
  • C Program Area Of Rhombus – 4 Ways | C Programs
  • C Program Area Of Isosceles Triangle | C Programs
  • C Program Area Of Square | C Programs
  • C Program To Find Area Of Semi Circle | C Programs
  • C Program To Find Volume of Sphere | C Programs
  • C Program Area Of Trapezium – 3 Ways | C Programs
  • C Program Area Of Parallelogram | C Programs
  • C Program Check A Character Is Upper Case Or Lower Case
  • Hollow Rhombus Star Pattern Program In C | Patterns
  • C Program To Count Total Number Of Notes in Given Amount
  • C Program Area Of Equilateral Triangle | C Programs
  • C Program to find the Area Of a Circle
  • C Program To Find Volume Of Cone | C Programs
  • C Program To Calculate Volume Of Cube | C Programs
  • C Program To Calculate Perimeter Of Rectangle | C Programs
  • C Program To Calculate Perimeter Of Rhombus | C Programs
  • C Program Volume Of Cuboid | C Programs
  • C Program To Calculate Perimeter Of Square | C Programs
  • C Program To Search All Occurrences Of A Character In String | C Programs
  • C Program Count Number Of Words In A String | 4 Ways
  • C Program To Left Rotate An Array | C Programs
  • C Program To Copy All Elements From An Array | C Programs
  • C Program To Toggle Case Of Character Of A String | C Programs
  • C Program To Delete Duplicate Elements From An Array | 4 Ways
  • C Program Inverted Right Triangle Star Pattern – Pattern Programs
  • C Program Volume Of Cylinder | C Programs
  • C Square Star Pattern Program – C Pattern Programs | C Programs
  • C Program To Remove First Occurrence Of A Character From String
  • C Program To Compare Two Strings – 3 Easy Ways | C Programs
  • C Program To Search All Occurrences Of A Word In String | C Programs
  • C Mirrored Right Triangle Star Pattern Program – Pattern Programs
  • C Program To Count Occurrences Of A Word In A Given String | C Programs
  • C Program To Find Reverse Of A string | 4 Ways
  • C Program To Delete An Element From An Array At Specified Position | C Programs
  • C Program To Reverse Words In A String | C Programs
  • C Program To Remove Last Occurrence Of A Character From String
  • C Programs – 500+ Simple & Basic Programming Examples & Outputs
  • C Pyramid Star Pattern Program – Pattern Programs | C
  • C Program Replace First Occurrence Of A Character With Another String
  • C Program Replace All Occurrences Of A Character With Another In String
  • C Program To Remove Repeated Characters From String | 4 Ways
  • C Plus Star Pattern Program – Pattern Programs | C
  • C Program To Find Last Occurrence Of A Word In A String | C Programs
  • Hollow Square Pattern Program in C | C Programs
  • C Program To Check A String Is Palindrome Or Not | C Programs
  • C Program To Remove Blank Spaces From String | C Programs
  • Rhombus Star Pattern Program In C | 4 Multiple Ways
  • C Program To Find Last Occurrence Of A Character In A Given String
  • C Program To Trim Leading & Trailing White Space Characters From String
  • C Program To Copy One String To Another String | 4 Simple Ways
  • C Program Number Of Alphabets, Digits & Special Character In String | Programs
  • Merge Two Arrays To Third Array C Program | 4 Ways
  • C Program To Find Maximum & Minimum Element In Array | C Prorams
  • C Program To Sort Even And Odd Elements Of Array | C Programs
  • C Program To Search An Element In An Array | C Programs
  • C Program Right Triangle Star Pattern | Pattern Programs
  • C Program To Count Frequency Of Each Character In String | C Programs
  • C Program Count Number Of Vowels & Consonants In A String | 4 Ways
  • C Program Find Maximum Between Two Numbers | C Programs
  • C Program To Count Frequency Of Each Element In Array | C Programs
  • C Program To Trim Trailing White Space Characters From String | C Programs
  • C Program To Trim White Space Characters From String | C Programs
  • Highest Frequency Character In A String C Program | 4 Ways
  • C Program To Find First Occurrence Of A Word In String | C Programs
  • C Program To Concatenate Two Strings | 4 Simple Ways
  • C Program To Remove First Occurrence Of A Word From String | 4 Ways
  • C Program To Insert Element In An Array At Specified Position
  • C Program To Convert Lowercase String To Uppercase | 4 Ways
  • C Program To Print All Unique Elements In The Array | C Programs
  • C Program To Put Even And Odd Elements Of Array Into Two Separate Arrays
  • C Program To Count Occurrences Of A Character In String | C Programs
  • C Program To Count Number Of Even & Odd Elements In Array | C Programs
  • C Program To Sort Array Elements In Ascending Order | 4 Ways
  • C Program To Count Number Of Negative Elements In Array
  • C Program Hollow Inverted Right Triangle Star Pattern
  • C Program To Convert Uppercase String To Lowercase | 4 Ways
  • C Program To Print Number Of Days In A Month | 5 Ways
  • Diamond Star Pattern C Program – 4 Ways | C Patterns
  • C Program To Input Week Number And Print Week Day | 2 Ways
  • C Program Hollow Inverted Mirrored Right Triangle
  • C Program To Remove All Occurrences Of A Character From String | C Programs
  • C Program Count Number of Duplicate Elements in An Array | C Programs
  • C Program To Find Sum Of All Array Elements | 4 Simple Ways
  • C Program To Find Lowest Frequency Character In A String | C Programs
  • C Program To Sort Array Elements In Descending Order | 3 Ways
  • 8 Star Pattern – C Program | 4 Multiple Ways
  • C Program To Read & Print Elements Of Array | C Programs
  • C Program To Replace Last Occurrence Of A Character In String | C Programs
  • C Program To Find Length Of A String | 4 Simple Ways
  • C Program To Right Rotate An Array | 4 Ways
  • C Program To Find First Occurrence Of A Character In A String
  • C Program Hollow Mirrored Rhombus Star Pattern | C Programs
  • C Program Half Diamond Star Pattern | C Pattern Programs
  • C Program Hollow Mirrored Right Triangle Star Pattern
  • Hollow Inverted Pyramid Star Pattern Program in C
  • C Program To Print All Negative Elements In An Array
  • Right Arrow Star Pattern Program In C | 4 Ways
  • C Program : Capitalize First & Last Letter of A String | C Programs
  • C Program Hollow Right Triangle Star Pattern
  • C Program : Check if Two Arrays Are the Same or Not | C Programs
  • C Program : Check if Two Strings Are Anagram or Not
  • Left Arrow Star Pattern Program in C | C Programs
  • C Program Mirrored Half Diamond Star Pattern | C Patterns
  • C Program Inverted Mirrored Right Triangle Star Pattern
  • Hollow Pyramid Star Pattern Program in C
  • C Program : Non – Repeating Characters in A String | C Programs
  • C Program : Sum of Positive Square Elements in An Array | C Programs
  • C Program : Find Longest Palindrome in An Array | C Programs
  • C Program : To Reverse the Elements of An Array | C Programs
  • C Program Lower Triangular Matrix or Not | C Programs
  • C Program : Maximum Scalar Product of Two Vectors
  • C Program Merge Two Sorted Arrays – 3 Ways | C Programs
  • C Program : Check If Arrays are Disjoint or Not | C Programs
  • C program : Find Median of Two Sorted Arrays | C Programs
  • C Program : Convert An Array Into a Zig-Zag Fashion
  • C Program : Minimum Scalar Product of Two Vectors | C Programs
  • C Program : Find Missing Elements of a Range – 2 Ways | C Programs
  • C Program Transpose of a Matrix 2 Ways | C Programs
  • C Program Patterns of 0(1+)0 in The Given String | C Programs
  • C Program : To Find Maximum Element in A Row | C Programs
  • C Program : To Find the Maximum Element in a Column
  • C Program : Rotate the Matrix by K Times | C Porgrams
  • C Program To Check Upper Triangular Matrix or Not | C Programs
  • C Program : Check if An Array Is a Subset of Another Array
  • C Program : Non-Repeating Elements of An Array | C Programs
  • C Program : Rotate a Given Matrix by 90 Degrees Anticlockwise
  • C Program Sum of Each Row and Column of A Matrix | C Programs

Learn Java Java Tutoring is a resource blog on java focused mostly on beginners to learn Java in the simplest way without much effort you can access unlimited programs, interview questions, examples

Java while loop – tutorial & examples.

in Java Tutorials March 6, 2024 Comments Off on Java While Loop – Tutorial & Examples

While Loop In Java – Executing a set of statements repeatedly is known as looping. We have 3 types of looping constructs in Java. These looping statements are also known as iterative statements.

All the three are used primarily with same purpose and the difference is in their syntax. Because of the syntactical differences, their behavior may differ a little bit. We will see the differences soon. More than the behavior it is programmer’s choice about what looping constructor to use when.

Example For While Loop – While Loop Basics

Definition Of While Loop

This loop is used to execute a set of statements repeatedly as long as a condition is true.

When control comes to this loop, the condition in the header is evaluated to check whether it results in true or false. If the condition is true, the control enters the loop body and executes the statements in it.

After executing the statements, the control automatically comes up to the condition part and checks whether the condition results in true (the code in body might have changed value of some variable so that the conditions truth value may change).

If the condition results in true, then control enters the body again to execute the statements in it. Then the control goes to condition part again.

This process is continued as long as the condition results in true . When the condition results in false, the control goes to the statement immediately following the loop.

Example Program for Java While Loop:

Execution Order:

Another Example Program For While Loop In Java:

In the above example, by the time control comes to header part of the loop, a is 1 and b is 3 so the condition a<=b results in true.

So the control comes into loop body and prints “mouse” . Then value of a is incremented by 1 so it becomes 2. Then the control comes-up to the condition part automatically and checks its truth value.

As value of a is 2 now, the condition results in true again. So the body executes and prints “mouse” again. Then a becomes 3.

Then the control comes to condition part again which results in true. So the loop body is executed third time to print “mouse” and to increment a by 1 .

This time a is 4 so the condition results in false (4<=3) . As the condition is false, the control comes to the statement after the loop and prints “cat”.

Loop Control Variables

The truth value of the condition depends on one or more variables. Such variables are known as loop control variables.

In the above example, the condition in loop header depends on the variable a and b. A change in any of these two variables will affect the truth value of the condition. In this particular example, value of b is not changed at all in the loop. So a is the primary loop control variable here.

Body With Single Statement

Similar to if/else block, the while loop block also do not need curly braces when there is only one statement. So the following two examples will give same effect.

Generally the loop body is executed N number of times and the condition is checked for N+1 number of times. For the first N times, the condition results in true and the (N+1)th time the condition results in false.

Infinite Loops

Sometimes we write a looping construct as if the condition results in true always. Such loops are known as infinite loops or indefinite loops.

Example Program For Infinite Loop:

This kind of loops are used when we don’t know exactly when to come out of the loop. At middle of the loop body, we may need to come out depending on a resultant value after an expression is evaluated or a user entered value met a condition. When such a situation arises we can come out using a statement like ‘break ’ or ‘return’.

Executing Part Of The Body In An Iteration

If we want to skip remaining statements of a loop in the current iteration (round), then we can use ‘continue’ statement at middle of a loop body. Then the control automatically goes to the next iteration (condition part). The next time (in the next iteration) all the statements of the loop body may get executed.

Only Boolean Values Are Accepted

The condition in the header should always result in a Boolean value (true or false). No other value is allowed (similar to condition in if header).

Nested Loops

We can have a looping construct inside another looping construct. This kind of arrangement is known as nested looping.

There is no limit on depth of nesting.  We can have any other loop inside a while loop. In fact any loop can have any other loop as part of its nesting. Not only a loop, any other construct (if, switch, etc) can be placed in a loop.

Initialization, Condition and Incrementation

Generally a loop execution depends on initial value of loop control variable, condition of loop and incrementation/decrementation of loop control variable.

The following loop executes for 10 times.

Dummy Statement As Loop Body

If we put a semi-colon at the end of a while expression, that semi-colon becomes body of the loop. In that case anything after the semi-colon becomes out of the loop.

In the above example we have 3 statements. int a=10; is before the loop and System.out.println(a); is after the loop.

The loop statement ends in its line itself. The semi-colon in the line (2nd line) is body of the loop. So as long as the condition (a++ < 13) is true the dummy statement (semi-colon) is executed.

When condition results in false , the control comes out to print a value. So the printing statement is executed only once with that code. When it is printed, it prints 14.

Hope you like this tutorial, In case if you have any doubts do leave a comment here.

Related Posts !

Java thread by extending thread class – java tutorials.

March 7, 2024

How to Read All Elements In Vector By Using Iterator

Remove an element from collection using iterator object in java.

java assignment while loop

30+ Number & Star Pattern Programs In Java – Patterns

Copying character array to string in java – tutorial, what is recursion in java programming – javatutoring.

March 6, 2024

Java If Else – Tutorial With Examples | Learn Java

If else Java – statement complete tutorial. Here we cover in-depth information with examples on ...

  • Java Tutorial
  • What is Java?
  • Installing the Java SDK
  • Your First Java App
  • Java Main Method
  • Java Project Overview, Compilation and Execution
  • Java Core Concepts
  • Java Syntax
  • Java Variables
  • Java Data Types
  • Java Math Operators and Math Class
  • Java Arrays
  • Java String
  • Java Operations
  • Java if statements
  • Java Ternary Operator
  • Java switch Statements
  • Java instanceof operator
  • Java for Loops

Java while Loops

  • Java Classes
  • Java Fields
  • Java Methods
  • Java Constructors
  • Java Packages
  • Java Access Modifiers
  • Java Inheritance
  • Java Nested Classes
  • Java Record
  • Java Abstract Classes
  • Java Interfaces
  • Java Interfaces vs. Abstract Classes
  • Java Annotations
  • Java Lambda Expressions
  • Java Modules
  • Java Scoped Assignment and Scoped Access
  • Java Exercises

The Java while Loop

The java do while loop, the continue command, the break command, variable visibility in while loops.

The Java while loop is similar to the for loop . The while loop enables your Java program to repeat a set of operations while a certain conditions is true.

The Java while loop exist in two variations. The commonly used while loop and the less often do while version. I will cover both while loop versions in this text.

Let us first look at the most commonly used variation of the Java while loop. Here is a simple Java while loop example:

This example shows a while loop that executes the body of the loop as long as the counter variable is less than 10. Inside the while loop body the counter is incremented. Eventually the counter variable will no longer be less than 10, and the while loop will stop executing.

Here is another while example that uses a boolean to make the comparison:

This Java while example tests the boolean variable shouldContinue to check if the while loop should be executed or not. If the shouldContinue variable has the value true , the while loop body is executed one more time. If the shouldContinue variable has the value false , the while loop stops, and execution continues at the next statement after the while loop.

Inside the while loop body a random number between 0 and 10 is generated. If the random number is larger than 5, then the shouldContinue variable will be set to true . If the random number is 5 or less, the shouldContinue variable will be set to false .

Like with for loops, the curly braces are optional around the while loop body. If you omit the curly braces then the while loop body will consist of only the first following Java statement. Here is a Java while example illustrating that:

In this example, only the first System.out.println() statement is executed inside the while loop. The second System.out.println() statement is not executed until after the while loop is finished.

Forgetting the curly braces around the while loop body is a common mistake. Therefore it can be a good habit to just always put them around the while loop body.

The second variation of the Java while loop is the do while construct. Here is a Java do while example:

Notice the while loop condition is now moved to after the do while loop body. The do while loop body is always executed at least once, and is then executed repeatedly while the while loop condition is true .

The main difference between the two while loop variations is exactly that the do while loop is always executed at least once before the while loop condition is tested. This is not the case with the normal while loop variation explained in the beginning of this text.

The two variations of the Java while loop come in handy in different situations. I mostly used the first while loop variation, but there are situations where I have used the second variation.

Java contains a continue command which can be used inside Java while (and for ) loops. The continue command is placed inside the body of the while loop. When the continue command is met, the Java Virtual Machine jumps to the next iteration of the loop without executing more of the while loop body. The next iteration of the while loop body will proceed as any other. If that iteration also meets the continue command, that iteration too will skip to the next iteration, and so forth.

Here is a simple continue example inside a while loop:

Notice the if statement inside the while loop. This if statement checks if each String in the strings array does not start with with the letter j . If not, then the continue command is executed, and the while loop continues to the next iteration.

If the current String in the strings array does start with the letter j , then the next Java statement after the if statement is executed, and the variable wordsStartingWithJ is incremented by 1.

The continue command also works inside do while loops. Here is a do while version of the previous example:

Notice that this version of the while loop requires that the strings array has a least one element, or it will fail when trying to index into the array at position 0 during the first iteration of the do while loop.

The break command is a command that works inside Java while (and for ) loops. When the break command is met, the Java Virtual Machine breaks out of the while loop, even if the loop condition is still true. No more iterations of the while loop are executed once a break command is met. Here is a break command example inside a while loop:

Notice the second if statement inside the while loop. This if statement checks if 3 words or more have been found which starts with the letter j . If yes, the break command is executed, and the program breaks out of the while loop.

Like with the continue command, the break command also works inside do while loops. Here is the example from before, using a do while loop instead:

Note that this variation of the while loop requires that the strings array always has at least one element. If not, it will fail during the first iteration of the do while loop, when it tries to access the first element (with index 0) of the array.

Variables declared inside a Java while loop are only visible inside the while loop body. Look at this while loop example:

After the while loop body has finished executing the count variable is still visible, since the count variable is declared outside the while loop body. But the name variable is not visible because it is declared inside the while loop body. Therefore the name variable is only visible inside the while loop body.

java assignment while loop

First Code School

  • Java Tutorials

While Loop in Java with examples

by FC Team · Published February 21, 2024 · Updated February 21, 2024

In this article, we will be taking a deep dive into the topic of while loop using Java programming language. As we move forward in this article, we will cover topics like the use of while loops and its syntax and get a better understanding of the while loop by looking at a schematic flowchart.

We will also be looking at some common examples of while loops using programs. The best results will come if you practice the codes shown in the article and also try some variations of the same codes to master the concept.

What is the use of a While loop in Java?

A while loop is a programming instruction that repeats a set of instructions as long as a condition is met. Once the boolean condition turns false, then the loop terminates, and the block of code is no longer performed.

You can think of a while loop as an If statement that repeats itself. While loops are often used in programming languages when the number of iterations is not known.

What is the Syntax of the Java while loop?

The syntax of the while loop is shown below:

Let us take a moment to understand the syntax of the while loop: The condition is the termination condition of the loop. This means that as long as the condition is true, The statements inside the loop are executed until the condition becomes false. When the condition becomes false, the loop terminates, and the set of instructions after the loop starts executing.

But how does the condition become false? Well, within the body of the loop, we will have an updation expression to change the parameters in the condition. With each iteration, the parameter changes, and the next time it enters the loop, it checks if the condition still holds true or not with the new value of the parameter.

Before we look at some example codes of the while loop, let’s perfectly understand the working of the while loop by looking at its flowchart:

while loop chart

Examples of While loop in Java

Now that we have established our basics, and know the working of the while loop perfectly, let us take a look at some common and simple codes that involve the while loop

1. Printing first n natural numbers

The below-shown code prints the first n numbers:

Enter the number of natural numbers you want to print: 7

1 2 3 4 5 6 7

In the code shown above, the condition in the while loop is that the value of “i” must always be less than the number specified by the user (n). Here, our updation expression is ”i++”, where we increment the variable and then check the condition after every iteration.

2. Sum of the first n natural numbers

Enter the number until which you want to find the sum: 10 The sum is 55

3. Infinite while loop

This is something that you typically want to avoid, the infinite while loop is a common problem programmers run into when the condition you have written in the while loop is wrong.

The reason a while loop goes into an infinite loop is that the loop never encounters a situation where it can terminate, and then we run into the issue of an infinite loop. The below code is an example of an infinite loop:

In this example, the condition states that “i is greater than or equal to 1” Since we started out with 5, and we keep incrementing the value of ‘i’, the condition never becomes false. Hence, the put will be a never-ending screen of numbers!!

Differences between a while loop and a do-while loop?

Both of them sound very similar, right? Well, they are not; they are substantially different. Let us take a look at the difference between both of the loops.

You have now learned and know everything you need to know to master while loops. We have discussed the use of the while loop its syntax with the help of a flowchart and a couple of programs to understand the while loop, including an infinite while loop.

Tags: java tutorials java while loop java while loop with examples learn java' while loop while loop in java

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Save my name, email, and website in this browser for the next time I comment.

  • Next story  Switch Statement in Java with Examples
  • Previous story  Java String getBytes() Method

Previous Section | Next Chapter | Main Index

Programming Questions and Exercises : Loops

Write a program to print numbers from 1 to 10.

Show the answer.

Write a program to calculate the sum of first 10 natural number.

Write a program that prompts the user to input a positive integer. It should then print the multiplication table of that number. 

Write a program to find the factorial value of any number entered through the keyboard. 

Two numbers are entered through the keyboard. Write a program to find the value of one number raised to the power of another. (Do not use Java built-in method)

Write a program that prompts the user to input an integer and then outputs the number with the digits reversed. For example, if the input is 12345, the output should be 54321.

Write a program that reads a set of integers, and then prints the sum of the even and odd integers.

Write a program that prompts the user to input a positive integer. It should then output a message indicating whether the number is a prime number. 

Write a program to calculate HCF of Two given number.

Question 10

Write a do-while loop that asks the user to enter two numbers. The numbers should be added and the sum displayed. The loop should ask the user whether he or she wishes to perform the operation again. If so, the loop should repeat; otherwise it should terminate. 

Question 11

Write a program to enter the numbers till the user wants and at the end it should display the count of positive, negative and zeros entered. 

Question 12

Write a program to enter the numbers till the user wants and at the end the program should display the largest and smallest numbers entered.

Question 13

Write a program to print out all Armstrong numbers between 1 and 500. If sum of cubes of each digit of the number is equal to the number itself, then the number is called an Armstrong number. For example, 153 = ( 1 * 1 * 1 ) + ( 5 * 5 * 5 ) + ( 3 * 3 * 3 )

Question 14

Write a program to print Fibonacci series of n terms where n is input by user : 0 1 1 2 3 5 8 13 24 ..... 

Question 15

Write a program to calculate the sum of following series where n is input by user.  1 + 1/2 + 1/3 + 1/4 + 1/5 +…………1/n 

Question 16

Compute the natural logarithm of 2, by adding up to n terms in the series 1 - 1/2 + 1/3 - 1/4 + 1/5 -... 1/n where n is a positive integer and input by user.

Question 17

Write a program that generates a random number and asks the user to guess what the number is. If the user's guess is higher than the random number, the program should display "Too high, try again." If the user's guess is lower than the random number, the program should display "Too low, try again." The program should use a loop that repeats until the user correctly guesses the random number.

Question 18

Write a program to print following :

Question 19

Write a program to compute sinx for given x. The user should supply x and a positive integer n. We compute the sine of x using the series and the computation should use all terms in the series up through the term involving x n

sin x = x - x 3 /3! + x 5 /5! - x 7 /7! + x 9 /9! .......

Question 20

Write a program to compute the cosine of x. The user should supply x and a positive integer n. We compute the cosine of x using the series and the computation should use all terms in the series up through the term involving x n

cos x = 1 - x 2 /2! + x 4 /4! - x 6 /6! .....

  • 1.1 Getting Started
  • 1.2 Creating Your First Application
  • 1.3 Parts of a Java Program
  • 1.4 Variables and Literals
  • 1.5 Primitive Data Types
  • 1.6 Arithmetic Operators
  • 1.7 Operator Precedence
  • 1.8 Type Conversion and Casting
  • Questions and Exercises
  • 2.1 Class String
  • 2.2 Objects and Reference Variables
  • 2.3 Class Math Methods
  • 2.4 String Methods
  • 2.5 Reading Keyboard Input
  • 2.6 Dialog Boxes for Input/Output
  • 3.1 The if-else Statement
  • 3.2 The if-else-if Statement
  • 3.3 Nested if Statement
  • 3.4 Logical Operators
  • 3.5 Comparing String Objects
  • 3.6 The switch Statement
  • 3.7 Conditional Operator
  • 4.1 The Increment and Decrement Operators
  • 4.2 The while Loop
  • 4.3 The do-while Loop
  • 4.4 The for Loop
  • 4.5 Nested Loops
  • 4.6 The break and continue Statements
  • 5.1 Introduction to Methods
  • 5.2 void Methods
  • 5.3 Passing Arguments to a Method
  • 5.4 Local Variables
  • 5.5 Returning a Value from a Method
  • 6.1 Objects and Classes
  • 6.2 Designing a Class
  • 6.3 Constructors
  • 6.4 Overloading Methods
  • 6.5 UML Diagram
  • 7.1 Introduction to Arrays
  • 7.2 Processing Array Elements
  • 7.3 Passing Arrays as Arguments to Methods
  • 7.4 Common Array Operations
  • 7.5 Returning Arrays from Methods
  • 7.6 String Arrays
  • 7.7 Arrays of Objects
  • 7.8 Two-Dimensional Arrays
  • 7.9 Variable-Length Argument Lists
  • 7.10 The ArrayList Class
  • 8.1 Static Class Members
  • 8.2 Passing Objects as Arguments to Methods
  • 8.3 Returning Objects from Methods
  • 8.4 The toString Method
  • 8.5 The this Reference Variable
  • 8.6 Aggregation
  • 8.7 Garbage Collection
  • 9.1 What Is Inheritance?
  • 9.2 Calling the Superclass Constructor
  • 9.3 Overriding Superclass Methods
  • 9.4 Protected Member
  • 9.5 Multilevel Inheritance
  • 9.6 The object Class
  • 9.7 Polymorphism
  • 9.8 Abstract Classes and Abstract Method
  • 9.9 Interfaces
  • 10.1 Introduction to File Input and Output
  • 10.2 Writing Data to Text File
  • 10.3 Reading Data from Text File
  • 10.4 Reading and Writing Premitive Data
  • 11.1 Handling Exception
  • 11.2 Try Catch Block and Multi Catch
  • 11.3 Finally Block
  • 11.4 Try with Resources
  • 11.5 Checked and Unchecked Exceptions
  • 11.6 Rethrowing and Throwing an Exception
  • 11.7 Creating Your Own Exception Classes

Home | Contact us | About us

Learn Java practically and Get Certified .

Popular Tutorials

Popular examples, reference materials, learn java interactively, java introduction.

  • Java Hello World
  • Java JVM, JRE and JDK
  • Java Variables and Literals
  • Java Data Types
  • Java Operators
  • Java Input and Output
  • Java Expressions & Blocks
  • Java Comment

Java Flow Control

  • Java if...else
  • Java switch Statement

Java for Loop

Java for-each Loop

  • Java while Loop
  • Java break Statement

Java continue Statement

  • Java Arrays
  • Multidimensional Array
  • Java Copy Array

Java OOP (I)

  • Java Class and Objects
  • Java Methods
  • Java Method Overloading
  • Java Constructor
  • Java Strings
  • Java Access Modifiers
  • Java this keyword
  • Java final keyword
  • Java Recursion
  • Java instanceof Operator

Java OOP (II)

  • Java Inheritance
  • Java Method Overriding
  • Java super Keyword
  • Abstract Class & Method
  • Java Interfaces
  • Java Polymorphism
  • Java Encapsulation

Java OOP (III)

  • Nested & Inner Class
  • Java Static Class
  • Java Anonymous Class
  • Java Singleton
  • Java enum Class
  • Java enum Constructor
  • Java enum String
  • Java Reflection
  • Java Exception Handling
  • Java Exceptions
  • Java try...catch
  • Java throw and throws
  • Java catch Multiple Exceptions
  • Java try-with-resources
  • Java Annotations
  • Java Annotation Types
  • Java Logging
  • Java Assertions
  • Java Collections Framework
  • Java Collection Interface
  • Java List Interface
  • Java ArrayList
  • Java Vector
  • Java Queue Interface
  • Java PriorityQueue
  • Java Deque Interface
  • Java LinkedList
  • Java ArrayDeque
  • Java BlockingQueue Interface
  • Java ArrayBlockingQueue
  • Java LinkedBlockingQueue
  • Java Map Interface
  • Java HashMap
  • Java LinkedHashMap
  • Java WeakHashMap
  • Java EnumMap
  • Java SortedMap Interface
  • Java NavigableMap Interface
  • Java TreeMap
  • Java ConcurrentMap Interface
  • Java ConcurrentHashMap
  • Java Set Interface
  • Java HashSet
  • Java EnumSet
  • Java LinkedhashSet
  • Java SortedSet Interface
  • Java NavigableSet Interface
  • Java TreeSet
  • Java Algorithms
  • Java Iterator
  • Java ListIterator
  • Java I/O Streams
  • Java InputStream
  • Java OutputStream
  • Java FileInputStream
  • Java FileOutputStream
  • Java ByteArrayInputStream
  • Java ByteArrayOutputStream
  • Java ObjectInputStream
  • Java ObjectOutputStream
  • Java BufferedInputStream
  • Java BufferedOutputStream
  • Java PrintStream

Java Reader/Writer

  • Java Reader
  • Java Writer
  • Java InputStreamReader
  • Java OutputStreamWriter
  • Java FileReader
  • Java FileWriter
  • Java BufferedReader
  • Java BufferedWriter
  • Java StringReader
  • Java StringWriter
  • Java PrintWriter

Additional Topics

  • Java Scanner Class
  • Java Type Casting
  • Java autoboxing and unboxing
  • Java Lambda Expression
  • Java Generics
  • Java File Class
  • Java Wrapper Class
  • Java Command Line Arguments

Java Tutorials

Nested Loop in Java

  • Java if...else Statement

Java while and do...while Loop

In computer programming, loops are used to repeat a block of code. For example, if you want to show a message 100 times, then you can use a loop. It's just a simple example; you can achieve much more with loops.

In the previous tutorial, you learned about Java for loop . Here, you are going to learn about while and do...while loops.

Java while loop

Java while loop is used to run a specific code until a certain condition is met. The syntax of the while loop is:

  • A while loop evaluates the textExpression inside the parenthesis () .
  • If the textExpression evaluates to true , the code inside the while loop is executed.
  • The textExpression is evaluated again.
  • This process continues until the textExpression is false .
  • When the textExpression evaluates to false , the loop stops.

To learn more about the conditions, visit Java relational and logical operators .

Flowchart of while loop

Flowchart of while loop in Java

Example 1: Display Numbers from 1 to 5

Here is how this program works.

Example 2: Sum of Positive Numbers Only

In the above program, we have used the Scanner class to take input from the user. Here, nextInt() takes integer input from the user.

The while loop continues until the user enters a negative number. During each iteration, the number entered by the user is added to the sum variable.

When the user enters a negative number, the loop terminates. Finally, the total sum is displayed.

Java do...while loop

The do...while loop is similar to while loop. However, the body of do...while loop is executed once before the test expression is checked. For example,

  • The body of the loop is executed at first. Then the textExpression is evaluated.
  • If the textExpression evaluates to true , the body of the loop inside the do statement is executed again.
  • The textExpression is evaluated once again.
  • This process continues until the textExpression evaluates to false . Then the loop stops.

Flowchart of do...while loop

Flowchart of do...while loop in Java

Let's see the working of do...while loop.

Example 3: Display Numbers from 1 to 5

Example 4: sum of positive numbers.

Here, the user enters a positive number, that number is added to the sum variable. And this process continues until the number is negative. When the number is negative, the loop terminates and displays the sum without adding the negative number.

Here, the user enters a negative number. The test condition will be false but the code inside of the loop executes once.

Infinite while loop

If the condition of a loop is always true , the loop runs for infinite times (until the memory is full). For example,

Here is an example of an infinite do...while loop.

In the above programs, the textExpression is always true . Hence, the loop body will run for infinite times.

for and while loops

The for loop is used when the number of iterations is known. For example,

And while and do...while loops are generally used when the number of iterations is unknown. For example,

Table of Contents

  • Introduction
  • Flowchart of while Loop
  • Example: while Loop
  • Java do...while Loop
  • Flowchart of do...while Loop
  • Example: do...while Loop
  • Infinite while Loop
  • Java for vs while loop

Sorry about that.

Related Tutorials

Java Tutorial

Logo for Rebus Press

Want to create or adapt books like this? Learn more about how Pressbooks supports open publishing practices.

Kenneth Leroy Busbee

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. [1]

Introduction to Test Before Loops

There are two commonly used test before loops in the iteration (or repetition) category of control structures. They are: while and for. This module covers the: while.

Understanding Iteration in General – while

The concept of iteration is connected to possibly wanting to repeat an action. Like all control structures we ask a question to control the execution of the loop. The term loop comes from the circular looping motion that occurs when using flowcharting. The basic form of the while loop is as follows:

In most programming languages the question (called a test expression) is a Boolean expression. The Boolean data type has two values – true and false. Let’s rewrite the structure to consider this:

Within the while control structure there are four attributes to a properly working loop. They are:

  • Initializing the flag
  • Test expression
  • Action or actions
  • Update of the flag

The initialization of the flag is not technically part of the control structure, but a necessary item to occur before the loop is started. The English phrasing is, “While the expression is true, do the following actions”. This is looping on the true. When the test expression is false, you stop the loop and go on with the next item in the program. Notice, because this is a test before loop the action  might not happen . It is called a test before loop because the test comes before the action. It is also sometimes called a pre-test loop, meaning the test is pre (or Latin for before) the action and update.

Human Example of the while Loop

Consider the following one-way conversation from a mother to her child.

Child: The child says nothing, but mother knows the child had Cheerios for breakfast and history tells us that the child most likely spilled some Cheerios on the floor.

Mother says: “While it is true that you see (As long as you can see) a Cheerio on the floor, pick it up and put it in the garbage.”

Note: All of the elements are present to determine the action (or flow) that the child will be doing (in this case repeating). Because the question (can you see a Cheerios) has only two possible answers (true or false) the action will continue while there are Cheerios on the floor. Either the child 1) never picks up a Cheerio because they never spilled any or 2) picks up a Cheerio and keeps picking up Cheerios one at a time while he can see a Cheerio on the floor (that is until they are all picked up).

Infinite Loops

At this point, it is worth mentioning that good programming always provides for a method to ensure that the loop question will eventually be false so that the loop will stop executing and the program continues with the next line of code.  However, if this does not happen, then the program is in an infinite loop.  Infinite loops are a bad thing. Consider the following code:

Pseudocode infinite loop

The programmer assigned a value to the flag before the loop which is correct. However, they forgot to update the flag. Every time the test expression is asked it will always be true. Thus, an infinite loop because the programmer did not provide a way to exit the loop (he forgot to update the flag). Consider the following code:

No matter what the user replies during the flag update, the test expression does not do a relational comparison but does an assignment. It assigns ‘y’ to the variable and asks if ‘y’ is true? Since all non-zero values are treated as representing true, the answer to the test expression is true. Viola, you have an infinite loop.

Counting Loops

The examples above are for an event controlled loop. The flag updating is an event where someone decides if they want the loop to execute again. Often the initialization sets the flag so that the loop will execute at least once.

Another common usage of the while loop is as a counting loop. Consider:

The variable counter is said to be controlling the loop.  It is set to zero (called initialization) before entering the while loop structure and as long as it is less than 5 (five); the loop action will be executed.  But part of the loop action uses the increment operator to increase counter’s value by one.  After executing the loop five times (once for counter’s values of: 0, 1, 2, 3 and 4) the expression will be false and the next line of code in the program will execute. A counting loop is designed to execute the action (which could be more than one statement) a set of given number of times. In our example, the message is displayed five times on the monitor. It is accomplished by making sure all four attributes of the while control structure are present and working properly. The attributes are:

Missing an attribute might cause an infinite loop or give undesired results (does not work properly).

Missing the flag update usually causes an infinite loop.

Variations on Counting

In the following example, the integer variable age is said to be controlling the loop (that is the flag). We can assume that age has a value provided earlier in the program. Because the while structure is a test before loop; it is possible that the person’s age is 0 (zero) and the first time we test the expression it will be false and the action part of the loop would never be executed.

Consider the following variation assuming that age and counter are both integer data type and that age has a value:

This loop is a counting loop similar to our first counting loop example. The only difference is instead of using a literal constant (in other words 5) in our expression, we used the variable age (and thus the value stored in age) to determine how many times to execute the loop. However, unlike our first counting loop example which will always execute exactly 5 times; it is possible that the person’s age is 0 (zero) and the first time we test the expression it will be false and the action part of the loop would never be executed.

  • cnx.org: Programming Fundamentals – A Modular Structured Approach using C++
  • Wikipedia: While loop ↵
  • Wikipedia: Infinite loop ↵

Programming Fundamentals Copyright © 2018 by Kenneth Leroy Busbee is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License , except where otherwise noted.

Share This Book

  • Trending Now
  • Foundational Courses
  • Data Science
  • Practice Problem
  • Machine Learning
  • System Design
  • DevOps Tutorial
  • Web Browser
  • Single Program Multiple Data (SPMD) Model
  • Hybrid Blockchain
  • SciPy - Cluster
  • How to Reduce Code Duplication in Scala?
  • Stacked Bar Chart With Selection Using Altair in Python
  • Git - Move Files
  • Git - LFS (Large File Storage)
  • Git - Hooks
  • 5 Best Email Marketing Software
  • Principal Components Analysis in Data Mining
  • How to Use FlycoSystemBar Library in Android App?
  • How to Handle Big Repositories with Git?
  • What are Bitcoin Mitigating Attacks?
  • How to Create a Waffle Chart in Excel
  • How to Add Trendline in Excel Chart
  • How To Create Dot Plots In Excel?
  • How To Create a Tornado Chart In Excel?
  • How to Fix “Failed to install the following Android SDK packages as some licenses have not been accepted” Error in Android Studio?

Assignment Operators in Programming

Assignment operators in programming are symbols used to assign values to variables. They offer shorthand notations for performing arithmetic operations and updating variable values in a single step. These operators are fundamental in most programming languages and help streamline code while improving readability.

Table of Content

What are Assignment Operators?

  • Types of Assignment Operators
  • Assignment Operators in C
  • Assignment Operators in C++
  • Assignment Operators in Java
  • Assignment Operators in Python
  • Assignment Operators in C#
  • Assignment Operators in Javascript
  • Application of Assignment Operators

Assignment operators are used in programming to  assign values  to variables. We use an assignment operator to store and update data within a program. They enable programmers to store data in variables and manipulate that data. The most common assignment operator is the equals sign ( = ), which assigns the value on the right side of the operator to the variable on the left side.

Types of Assignment Operators:

  • Simple Assignment Operator ( = )
  • Addition Assignment Operator ( += )
  • Subtraction Assignment Operator ( -= )
  • Multiplication Assignment Operator ( *= )
  • Division Assignment Operator ( /= )
  • Modulus Assignment Operator ( %= )

Below is a table summarizing common assignment operators along with their symbols, description, and examples:

Assignment Operators in C:

Here are the implementation of Assignment Operator in C language:

Assignment Operators in C++:

Here are the implementation of Assignment Operator in C++ language:

Assignment Operators in Java:

Here are the implementation of Assignment Operator in java language:

Assignment Operators in Python:

Here are the implementation of Assignment Operator in python language:

Assignment Operators in C#:

Here are the implementation of Assignment Operator in C# language:

Assignment Operators in Javascript:

Here are the implementation of Assignment Operator in javascript language:

Application of Assignment Operators:

  • Variable Initialization : Setting initial values to variables during declaration.
  • Mathematical Operations : Combining arithmetic operations with assignment to update variable values.
  • Loop Control : Updating loop variables to control loop iterations.
  • Conditional Statements : Assigning different values based on conditions in conditional statements.
  • Function Return Values : Storing the return values of functions in variables.
  • Data Manipulation : Assigning values received from user input or retrieved from databases to variables.

Conclusion:

In conclusion, assignment operators in programming are essential tools for assigning values to variables and performing operations in a concise and efficient manner. They allow programmers to manipulate data and control the flow of their programs effectively. Understanding and using assignment operators correctly is fundamental to writing clear, efficient, and maintainable code in various programming languages.

Please Login to comment...

  • Programming
  • WhatsApp To Launch New App Lock Feature
  • Node.js 21 is here: What’s new
  • Zoom: World’s Most Innovative Companies of 2024
  • 10 Best Skillshare Alternatives in 2024
  • 30 OOPs Interview Questions and Answers (2024)

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

IMAGES

  1. While Loop in Java

    java assignment while loop

  2. Java Loops

    java assignment while loop

  3. Java do while loop

    java assignment while loop

  4. Java while loop com exemplos

    java assignment while loop

  5. The While Loop in Java

    java assignment while loop

  6. The Do While Loop in Java

    java assignment while loop

VIDEO

  1. Java Programming Session 08

  2. Loops in Java

  3. 11. Java While Loop, Example programs

  4. for loop java explanation #shorts

  5. JAVA

  6. JAVA

COMMENTS

  1. Assign variable in Java while-loop conditional?

    LiamRyan. 1,890 5 32 62. The difference between PHP and Java here is that while in Java requires a boolean-typed expression ( someVar = boolExpr is itself a boolean-typed expression). If the variable assigned was a bool then it would be identical. Please show the current Java code as it is likely that something of non-bool is being assigned.

  2. Java while loop with Examples

    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.

  3. Java While Loop

    The while loop is Java's most fundamental loop statement. It repeats a statement or a block of statements while its controlling Boolean-expression is true.. The syntax of the while loop is:. while (Boolean-expression) statement; The loop's Boolean-expression is evaluated before the first iteration of the loop - which means that if the condition is evaluated to false, the loop might not ...

  4. Java While Loop

    Java While Loop. The while loop loops through a block of code as long as a specified condition is true: Syntax while (condition) { // code block to be executed} In the example below, the code in the loop will run, over and over again, as long as a variable (i) is less than 5:

  5. The while and do-while Statements (The Java™ Tutorials

    The while statement evaluates expression, which must return a boolean value. If the expression evaluates to true, the while statement executes the statement(s) in the while block. The while statement continues testing the expression and executing its block until the expression evaluates to false.Using the while statement to print the values from 1 through 10 can be accomplished as in the ...

  6. Java While Loop

    while(a<=b) {. System.out.println( " mouse "); a++; } System.out.println( " cat "); In the above example, by the time control comes to header part of the loop, a is 1 and b is 3 so the condition a<=b results in true. So the control comes into loop body and prints "mouse". Then value of a is incremented by 1 so it becomes 2.

  7. Java while Loop (with Examples)

    The while loop in Java continually executes a block of statements until a particular condition evaluates to true. As soon as the condition becomes false, the while loop terminates. As a best practice, if the number of iterations is not known at the start, it is recommended to use the while loop. 1. Syntax. The syntax of while loop is:

  8. Java while Loops

    The Java while loop is similar to the for loop.The while loop enables your Java program to repeat a set of operations while a certain conditions is true.. The Java while loop exist in two variations. The commonly used while loop and the less often do while version. I will cover both while loop versions in this text.. The Java while Loop. Let us first look at the most commonly used variation of ...

  9. Is doing an assignment inside a condition considered a code smell?

    Many times I have to write a loop that requires initialization of a loop condition, and an update every time the loop executes. ... Java or C# that I know of to get rid of the duplication between initializer and incrementer. ... however the problem is that you can't clearly understand Why there is an assignment within the while statement unless ...

  10. While loop in Java with examples

    After fourth iteration: value of i is 4, the condition i<4 returns false so the loop ends and the code inside body of while loop doesn't execute. Practice the following java programs related to while loop: Java Program to display Fibonacci Series using while loop; Java Program to find factorial using while loop

  11. While Loop in Java with examples

    Output: In the code shown above, the condition in the while loop is that the value of "i" must always be less than the number specified by the user (n). Here, our updation expression is "i++", where we increment the variable and then check the condition after every iteration. 2. Sum of the first n natural numbers.

  12. Why would you use an assignment in a condition?

    The reason is: Performance improvement (sometimes) Less code (always) Take an example: There is a method someMethod () and in an if condition you want to check whether the return value of the method is null. If not, you are going to use the return value again. If(null != someMethod()){.

  13. Questions and Exercises in Loops

    Question 10. Write a do-while loop that asks the user to enter two numbers. The numbers should be added and the sum displayed. The loop should ask the user whether he or she wishes to perform the operation again. If so, the loop should repeat; otherwise it should terminate. Show the answer.

  14. Java while and do...while Loop

    Java while loop. Java while loop is used to run a specific code until a certain condition is met. The syntax of the while loop is:. while (testExpression) { // body of loop } Here, A while loop evaluates the textExpression inside the parenthesis ().; If the textExpression evaluates to true, the code inside the while loop is executed.; The textExpression is evaluated again.

  15. Java Assignment Operators with Examples

    variable operator value; Types of Assignment Operators in Java. The Assignment Operator is generally of two types. They are: 1. Simple Assignment Operator: The Simple Assignment Operator is used with the "=" sign where the left side consists of the operand and the right side consists of a value. The value of the right side must be of the same data type that has been defined on the left side.

  16. While loop in Programming

    While loop is a fundamental control flow structure in programming, enabling the execution of a block of code repeatedly as long as a specified condition remains true. While loop works by repeatedly executing a block of code as long as a specified condition remains true. It evaluates the condition before each iteration, executes the code block if the condition is true, and terminates when the ...

  17. Java While Loop

    A while statement looks like below. In Java, a while loop consists of the keyword while followed by a Boolean expression within parentheses, followed by the body of the loop, which can be a single statement or a block of statements surrounded by curly braces. while (expression) {// do stuff} You can use a while loop when you need to perform a ...

  18. java

    1. primes.length is always 200 so the while loop is never entered. The while loop is useless. Just add a condition to the for loop that would exit when the entire array has been assigned. Also move the initialization of primeCounter to be outside the for loop. Otherwise all the primes will be assigned to primes [0].

  19. While Loop

    The basic form of the while loop is as follows: initialization of the flag. while the answer to the question is true then do. some statements or action. some statements or action. some statements or action. update the flag. In most programming languages the question (called a test expression) is a Boolean expression.

  20. c

    I'm curious about expression used as condition for while loop: while (c = getchar(), c != EOF && c != 'x') ... Using the assignment operator in a while loop condition in C. 0. While loop doesn't execute statements at each iteration. 0. Assigning value inside while condition. 4.

  21. Assignment Operators in Programming

    Assignment operators are used in programming to assign values to variables. We use an assignment operator to store and update data within a program. They enable programmers to store data in variables and manipulate that data. The most common assignment operator is the equals sign (=), which assigns the value on the right side of the operator to ...

  22. Homework assignment using loops to count (Java)

    The assignment is... Write a while loop that prints 1 to userNum, using the variable i. Follow each number (even the last one) by a space. Assume userNum is positive. Ex: userNum = 4 prints:...