Java while loop | Java do while loop with Syntax & Examples

Java While loop is executed the same statement (block of code) until a given condition with while expression, is true. You will learn in this tutorial about how to create a while do and while loop in Java Programming.

As same, all loop in a Programming language has worked on the same scenario – “Repeat a specific block of code until a certain condition is false”

Java while loop and Java do while loop with Syntax & Examples

Syntax – while loop

Here is Java while loop syntax. Where expression is a Boolean type.

Flow Diagram of while Loop

How java while loop works, syntax and examples, flow diagram

How while loop works?

An Expression has used in while is a boolean expression.

  • If the expression is evaluated true then go inside
  • Follow the statement code then again evaluate express until false.

Java while loop program example

A simple example creating “i” variables and initialize with int 5 value.  Then add condition expression in while loop to run a loop until “i” is greater than 0. And i is decreasing by on every cycle completion of the loop.

Output: 5

do while loop in Java

It’s an Interesting part you use a Java do-while loop because it’s executed at least once.

Why It executes at least one time?

Because the condition is checked after the loop body, check the below example of how Java do while loop used.

Output: 5

Java while loop continues

You can use a continue keyword (statement) in all Java loops – for loop, while loop and do-while loop.

continue statement is used when you want immediately a jump to the next iteration in the loop. Let’s see the example program Java while loop continues.

Output: 0

Do while loop practice problems in java to crack the written test in Interview.

Loop control statements make very interesting and important, let’s think about you want a print 1 to 100 numbers. Then how you will do it? Absolutely doing write down every time System.out.print(“1”); is a very long and lengthy process.

That time you can use Java Lop Control Statements, where it will full fill your requirements. It’s the only example for 100-time print, in a big corporation there is million of data and for use search or filter them you have to use many methods again and again or query to add data in the database. So loop statement help to archive that all problem in easy and less code.

Do comment if you have any doubts and questions on this tutorial.

Note: This example (Project) is developed in IntelliJ IDEA 2018.2.6 (Community Edition)
JRE: 11.0.1
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
macOS 10.14.1

Java version 11

All Examples loops are in Java 11, so it may change on different from Java 9 or 10 or upgraded versions.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.