Saturday, 7 June 2025

What’s the Difference Between for Loop and while Loop in Java?

 Loops are a big part of Java — they help us repeat things. But many beginners get confused between for loops and while loops.

So here’s a quick breakdown of how they’re different and when to use each one.

for Loop

  • Used when you know how many times you want to loop.

  • Syntax:

    for (int i = 0; i < 5; i++) {

        System.out.println("Hello!");

    }

  • Best for counting or looping a fixed number of times.

    while Loop

    • Used when you don’t know how many times you’ll need to loop — but you keep looping until a condition is false.

    • Syntax:

      boolean t = true;
      int i = 0;
      while(t)
      {

      i++;

    • Best for things like waiting for a user input or looping until a goal is reached.

No comments:

Post a Comment

👨‍💻 How I Started Learning Java at 15 (and You Can Too)

  When I first heard of Java, I thought it was just something to do with Minecraft mods or Android apps. I didn’t realize it would become my...