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