How to Java: E5 (For Loops)

E5 (For Loops)

How to Java: E5 (For Loops)


Today, we'll be learning about for loops in Java: What they are, how they work, and how to create them.
Lets begin

In Java, like many other programming languages, we have Loops, which are functions that repeat the statement(s) within their brackets until something within the loop tells it to stop going.

In Java, we have 3 main ones: for loops, while loops, and do while loops. In today's lesson we'll be learning about FOR loops.

What Is A For Loop

A for loop is one of the 3 main loops that Java has. It is often the first one learned. It is used for allowing a statement/statements to constantly execute until something tells it to stop.

Here's a diagram:

Image via

How A For Loop Works
In for loops, the loop will keep looping until the condition, the part in the picture that says:
for(int i = 0; i < 10; i++){

This loop translates into:

  1. Instantiate the variable "i" and set the initial value equal to "0"
  2. Check the condition. In this case, is 0 less than 10? Yes
  3. Since the condition in Step 2 is true, the doStuff() statement within the loop's brackets is executed
  4. Increment "i" by 1 (because i++ translates to: (new) i = (current i) + 1
  5. Repeat step 2, but this time with i = 1
  6. If the current value of "i" is less than 10, Repeat step 3
  7. This keeps going on and on until i is no longer less than 10 (so in this case, the loop stops at i = 9 (because i<10 is not the same as i<= 10)

Creating Your First FOR Loop
Now obviously, like everything we've done up to this point, we need:

  • a Java class
  • a main method (of course for loops can exist in any method, you cannot write one directly within the class they MUST be inside of a function

Assuming you have read How To Java: E4 (Methods), go ahead and create your Java class and main method

Inside of the main method, lets create a for loop that prints out all non-decimal numbers from 1 to 10

I set my looping value to "i", but you can always set it to anything you want.

Next, lets write:

Assuming you wrote it correctly, run the method, you should see:

This is because we are using println(), the ln in println means "print line", so for each value within the parentheses printed, it goes to a new line

Of course, we can always change System.out.println(i); to System.out.print(i);, and we'll get:


This concludes today's How To Java tutorial.

The code for this lesson is available on GITHUB


Be the First to Comment

Share Your Thoughts

  • Hot
  • Latest