PGoCareerGoCareer prep tools
Home
LoginSign up
  • Java
  • Python
  • AI
  • React
  • Angular
  • PHP
  • Node.js
  • SQL
  • DSA
  • HTML
  • CSS
  • JS
  • Spring
  • ML
  • MongoDB

Java · Theory

Java While Loop

← All stacks

Theory

20/270

Java While Loop

while repeats as long as a condition stays true. Check first. If the condition is already false, the body never runs. Shape: while (condition) { body }.

Something inside the body must move toward stopping — i++, or a new input — or the loop never ends. while is good when the count is not known: keep reading until the user types stop.

for is better with a counter. while is better with “until this becomes false”. Contrast with do-while: while can run zero times; do-while runs at least once.

Let's take this on the board with one tiny Main class — no extra files. Java While Loop — output: 1 then 2 then 3. i starts at 1. When i becomes 4, i<=3 is false — loop stops. Start from main, go line by line, and stop at each print. That output is the proof for While Loop.

Diagram
check first ── false → stop
         │ true
         ▼
       body
         │
         └── check again
Exam tip

Contrast while (check first) vs do-while (body first).

Example

// Java While Loop — prints 1, 2, 3
public class Main {
  public static void main(String[] args) {
    int i = 1;
    while (i <= 3) {
      System.out.println(i);
      i++;
    }
  }
}

Java While Loop — output: 1 then 2 then 3. i starts at 1. When i becomes 4, i<=3 is false — loop stops.

Short notes

  • Defwhile repeats while the condition is true. Check happens first.
  • RuleUpdate the variable inside the body or it loops forever.
  • Rememberwhile can run 0 times. do-while runs at least once.
  • UseRead until stop, wait until a goal is met.

Questions

1

When does while check the condition?

2

Can while run zero times?

3

What happens if you forget to update?

Previous← For-Each Loop in JavaNextJava Do-While Loop →
P

GoCareerGo

Utilities · Preparation Hub · Resume · CV · Tools — one workspace.

Workspace

DashboardProfilePreparation HubResume builderCV builderCareer planning

PDF Tools

Merge PDFSplit PDFCompress PDFImage to PDFAll toolsJobs

Image & QR

Compress ImageResize ImageQR ScannerQR GeneratorBlogIT interview prep

Company

FAQFeedbackContactPrivacyTermsSitemap

© 2026 GoCareerGo. Keep moving forward.