Buzz Code
Published in

Buzz Code

Java 8 | For statement

For — Repeating a part of the program until its condition becomes false.

Hi guys! Today I’m going to talk about the For statement which is one of the most important control flow statements along with the If statement. Those two can be anywhere in a lot of programming languages, so let’s try to be super focused today. And before you go, you would need the basic knowledge of operators today, so if you don’t know how operators work please read my post below.


For statement is also known as the For loop. Just like its name, it can execute the block of statements repeatedly as long as its condition is true. Here I used the word block, it means a group of one or more statements enclosed in braces{}.

This is what the For statement looks like, you have to initialize the variable first, and set the condition, and then put the increment or decrement with the unary operators(++,--) .

Let’s say there’s a program that prints 0 to 9 on the console. The reading order of that For loop is right on below.

Sorry guys! I modified the explanation a bit!-201217

Like this, Initialization (1) works only once at the beginning, and if the condition (2) is true, move to (3) and execute the statements in the block of the For loop. And move to (4) to increment or decrement the variable’s value.
In this case, I declared the variable i’s initial value as 0, So i is less than 10. Since (2) is true, it goes to (3). So the first i will be printed as 0. And move to (4) to make i bigger.
I hope you remember that i++ means i = i+1 and again = is not equal sign here, it’s assignment operator. So i’s value becomes 1.
And then go back to (2) and check if the condition is still true, and (3) execute the statement, and then (4) increase i again. Repeat(2),(3),(4) as long as (2) is true!

You see the numbers are well printed on the console. But the thing is when you declared the variable at the inside of the For statement, that variable can only exist in that For statement.

Like here, the variable i is declared inside of the For statement, so on the outside of the block, that variable i doesn’t exist!

It’s bit tricky to read the For statement, but soon you’ll get familiar with this concept. To help that I’ll get you some practice questions of For statement next time. Well done today guys! See ya!



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store