How to use For Loop in Java
For Loop in Java is easy as 1 2 3. When you want your code to be executed dynamically instead of doing it manually, use for loop.
Syntax
for (statement 1; statement 2; statement 3) { //code block }
Statement 1: Sets a variable with a value. The loop start from here.
Statement 2: This is where you set your condition. Define the condition to run the loop. If the condition is true, It will keep running until it is false.
Statement 3: Increases a value every time until it reaches the end value of the condition or loop.
Example
When you are printing numbers from 1 – 5. Do not code like this. See this example code below.
System.out.println("1"); System.out.println("2"); System.out.println("3"); System.out.println("4"); System.out.println("5");
Output
1 2 3 4 5
Although, the output is the same as expected. But it seems like not a professional one. Your code should be like this.
for (int i = 1; i <= 5; i++) { System.out.println(i); }
Output
1 2 3 4 5