Sup?
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:
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++){
doStuff();
}
This loop translates into:
- Instantiate the variable "i" and set the initial value equal to "0"
- Check the condition. In this case, is 0 less than 10? Yes
- Since the condition in Step 2 is true, the doStuff() statement within the loop's brackets is executed
- Increment "i" by 1 (because i++ translates to: (new) i = (current i) + 1
- Repeat step 2, but this time with i = 1
- If the current value of "i" is less than 10, Repeat step 3
- 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:
System.out.println(i);
Assuming you wrote it correctly, run the method, you should see:
1
2
3
4
5
6
7
8
9
10
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:
12345678910
----------------------------------
This concludes today's How To Java tutorial.
The code for this lesson is available on GITHUB
-VoidX
Just updated your iPhone to iOS 18? You'll find a ton of hot new features for some of your most-used Apple apps. Dive in and see for yourself:
Be the First to Comment
Share Your Thoughts