Loops in Java - Super Easy Notes
1. What is a Loop?
A loop is used to repeat a block of code multiple times.
Example: Instead of writing print 5 times, use a loop to repeat it automatically.
2. Types of Loops in Java
There are 3 main loops in Java:
1. while loop
2. do-while loop
3. for loop
3. while Loop
Repeats as long as the condition is true.
Example:
int i = 1;
while (i <= 3) {
System.out.println("Hi");
i++;
4. do-while Loop
Runs at least once, even if the condition is false.
Example:
int i = 5;
do {
System.out.println("Bye");
i++;
} while (i < 5);
Loops in Java - Super Easy Notes
5. for Loop
Best when you know how many times to repeat.
Example:
for (int i = 1; i <= 5; i++) {
System.out.println("Java");
6. Which Loop to Use?
- Use for loop when you know the number of times
- Use while when you don't know how many times
- Use do-while when it must run at least once
7. Summary
Loop Type | When it runs | Best for
-------------------------------------------------
while | While condition is true | Unknown repeats
do-while | Always runs once first | Must run once
for | Fixed times | Counting, known repeats
8. Example: Print 1 to 5
for (int i = 1; i <= 5; i++) {
System.out.println(i);