Java Loops: Repeat Actions with For and While Loops
This tutorial will walk you through the basics of loops in Java, focusing on the for and while loops. Loops allow you to repeat a block of code multiple times. We’ll build three examples, starting with a simple counter and progressing to a more interactive scenario.
Example 1: Simple For Loop – Counting to 10
This example demonstrates the fundamental structure of a for loop. We’ll use it to print numbers from 1 to 10.
public class ForLoopExample {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
System.out.println("Iteration: " + i);
}
}
}
Let’s break down this code:
public class ForLoopExample: This declares a class named `ForLoopExample`. In Java, all code resides within classes.public static void main(String[] args): This is the main method, the entry point of the program. When you run the program, the code inside this method will be executed.for (int i = 1; i <= 10; i++): This is theforloop statement. It has three parts:- Initialization:
int i = 1– This initializes a counter variableito 1. This happens only once at the beginning of the loop. - Condition:
i <= 10– This is the condition that is checked before each iteration. As long asiis less than or equal to 10, the loop will continue. - Increment:
i++– This is executed after each iteration of the loop.i++increments the value ofiby 1. System.out.println("Iteration: " + i);: This line prints the current value ofito the console. The string “Iteration: ” is concatenated with the value ofi.
How it works:
- Initially,
iis set to 1. - The condition
i <= 10(1 <= 10) is evaluated. It is true. - The code inside the loop (
System.out.println("Iteration: " + i);) is executed, printing “Iteration: 1”. iis incremented to 2.- The condition
i <= 10(2 <= 10) is evaluated. It is true. - The code inside the loop is executed again, printing “Iteration: 2”.
- This process continues until
ibecomes 11. - When
iis 11, the conditioni <= 10(11 <= 10) is evaluated. It is false. - The loop terminates.
Potential Mistake: A common mistake is to omit the increment step (i++) or to use an incorrect increment value. This can lead to an infinite loop, where the loop never terminates.
Correction: Always ensure that the increment step is present and that the increment value is appropriate for your needs. In this case, incrementing by 1 is correct.
public class ForLoopExample {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
System.out.println("Iteration: " + i);
}
}
}
Output:
Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4
Iteration: 5
Iteration: 6
Iteration: 7
Iteration: 8
Iteration: 9
Iteration: 10
Example 2: While Loop – User Input
This example demonstrates a while loop, which continues as long as a specified condition is true. It takes user input until the user enters a specific value (e.g., “quit”).
public class WhileLoopExample {
public static void main(String[] args) {
String input = "";
while (!input.equalsIgnoreCase("quit")) {
System.out.println("Enter a command (or 'quit' to exit):");
input = System.console().readLine();
System.out.println("You entered: " + input);
}
System.out.println("Exiting the program.");
}
}
Explanation:
String input = "";: Initializes a string variableinputto an empty string.while (!input.equalsIgnoreCase("quit")): This is thewhileloop statement. It continues as long as the condition!input.equalsIgnoreCase("quit")is true.input.equalsIgnoreCase("quit")compares the value ofinputto “quit” (case-insensitive). The!negates the result.System.out.println("Enter a command (or 'quit' to exit):");: Prompts the user to enter a command.input = System.console().readLine();: Reads the user’s input from the console and stores it in theinputvariable.System.console()gets the console object, andreadLine()reads a line of text from the console.System.out.println("You entered: " + input);: Prints the user’s input to the console.
How it works:
- The loop starts with
inputbeing an empty string (“”). - The condition
!input.equalsIgnoreCase("quit")is evaluated. Since the string is empty, it’s not equal to “quit”, so the condition is true. - The loop body is executed, prompting the user for input and printing the input.
- The user enters a command (e.g., “hello”).
- The loop continues, and the user enters another command (e.g., “quit”).
- The condition
!input.equalsIgnoreCase("quit")is evaluated. Sinceinputis now “quit”, the condition is false. - The loop terminates.
public class WhileLoopExample {
public static void main(String[] args) {
String input = "";
while (!input.equalsIgnoreCase("quit")) {
System.out.println("Enter a command (or 'quit' to exit):");
input = System.console().readLine();
System.out.println("You entered: " + input);
}
System.out.println("Exiting the program.");
}
}
Output (example):
Enter a command (or 'quit' to exit):
You entered: hello
Enter a command (or 'quit' to exit):
You entered: quit
Exiting the program.
Example 3: Nested Loops – Printing a Square
This example demonstrates nested for loops to print a square of asterisks. This is a more complex demonstration of how loops can be combined.
public class NestedLoopsExample {
public static void main(String[] args) {
int size = 5; // Size of the square
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
System.out.print("");
}
System.out.println(); // Move to the next line after each row
}
}
}
Explanation:
int size = 5;: Defines the size of the square (number of rows and columns).for (int i = 0; i < size; i++): The outer loop iterates through the rows of the square.for (int j = 0; j < size; j++): The inner loop iterates through the columns of the square for each row.System.out.print("");: Prints an asterisk without moving to the next line.System.out.println();: Prints a newline character after each row is complete, moving the cursor to the beginning of the next line.
How it works:
- The outer loop iterates from
i = 0toi = 4. - For each value of
i, the inner loop iterates fromj = 0toj = 4. - Inside the inner loop, an asterisk is printed for each column. So, when
i = 0, you get “. Wheni = 1, you get ` ` and so on. - After the inner loop completes for a given
i,System.out.println();moves the cursor to the next line.
public class NestedLoopsExample {
public static void main(String[] args) {
int size = 5; // Size of the square
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
System.out.print("");
}
System.out.println(); // Move to the next line after each row
}
}
}
Output:



Leave a Reply