The course is part of this learning path
In this course, we look at control flow statements in the Java programming language.
- Decision-making statements
- Looping statements
- Branching statements
- Anyone looking to get Oracle Java Certification
- Those who want to learn the Java Programming language from scratch
- Java developers who want to increase their knowledge
- Beginners with no previous coding experience in Java programming
- Those who want to learn tips and tricks in Oracle Certified Associate – Java SE 8 Programmer certification exams
- No prior knowledge is required about the Java programming language.
- Basic computer knowledge
Hi there. In this video, we'll learn about the for loop. When you need to execute a block of code several times, we use looping statements. First, we'll learn how to use for loop in Java. The for loop is a control flow statement that iterates a part of the program multiple times. The general form of the for statement can be expressed in the slide. Initialization declares the initial value of the controlling variable. The controlling variable can be defined in line with the for loop or defined previously. Typically, the for loop uses an integer variable. Condition is a boolean expression. It must result in either a true or false output. If the condition is true, the loop continues to execute.
Relational operators are used in the boolean expression. After each execution of the statements, the control variable is updated according to the increment or decrement. Also, you see for loop execution flow on the slide. The first step, in for loop, the initialization part only executes once. Second step, condition in for loop is evaluated on each iteration. If the condition is true, then the loop body gets executed. If the condition returns false, statements in the loop body do not execute and control gets transferred to the next statement in the program after for loop. Third step, after each execution of for loop's body, the increment or decrement part of the for loop updates the value of the controlling variable. The last step, after the third step, the control jumps to the second step and the condition is re-evaluated.
Let's make some examples with for loop. In exercise project, right click on the source folder and select "New class". Specify the package name as loop and class name as ForLoop, and select the checkbox for the main method. Let's start to write the program that prints int numbers from 0 to 10 by using for loop. Let's declare a variable i. We initialize this variable in for loop. Our condition is i <= 10 and it increments by 1. We use the print method to write the numbers to screen. Okay. Let's run the code. You see the numbers from 0 to 10. Here, the variable i is declared and initialized to 0. Then, the test condition is evaluated. If this condition is true, the body of for loop is executed and prints 0 on the screen. Then, the update expression i++ is executed. Now, the value of i is increased to 1.
Again, the test condition is evaluated. 1 < 10, so the condition is true and the body of for loop is executed and prints 1 on the screen. The iteration process runs until i is 11. When i is 11, since 11 is greater than 10, the test condition is false and for loop terminates. So, you can change this increment like that, ++i. It's valid. Let's run and see. As you can see, the result is the same or you can write the increment like that, i+ = 1. That is also valid. Let's run and see. As you can see, the result is the same. Let's print the last value of the i variable. Outside the for loop, I write, System.out.println("Last value of i = " + i);. Now, let's run the code again. As you can see, the last value of the i is 11. But if you notice, we declared the i variable outside the for loop. If we move it inside the for loop, so if we initialize it like this, int i = 0; This time we get a compilation error because we declared the variable in the for loop and we can use it only inside the for loop.
This is the scope subject. We will learn this subject in the next lectures. Okay. Let's write another program. First, I'll turn these codes to the comment line. Now, let's write a program to find the sum of numbers 1 to 5. Let's declare a variable sum and assign the 0 to the initial value of this variable. In for loop, we use variable k and we declare and initialize variable k with 0 value. Our test condition is k < 6; and it increments by 1. So, I write k++. Now, we can write the code. First, we'll assign sum += k to variable sum with add and assignment operator.
If you remember, this syntax is equal to sum = sum + k. The value of k is increased until k is greater than 5. Let's print the value of k in the for loop by using the print method. Finally, we use the print method after the for loop to display the sum of numbers. System.out.println("The sum of the numbers = " + sum); Okay. Let's run the code. You see the values of k and the sum of numbers is 15. Okay. Let's write a program to find the sum of even numbers from 1 to 10. First, I'll copy the previous code and paste them here, and I'll turn the previous loop to the comment line. Now, let's make some changes for the test condition and the increment/decrement part.
The test condition will be 11. If you change the operator here to less than or equal to operator, this time the condition will be 10. Pay attention to this. And k increments by 2 because we will calculate the sum of the even numbers and the even numbers increased by 2. So, the variable k is always an even number. Finally, we use the print method after for loop to display the sum of even numbers. So, add the even word here. Okay. Let's run the code. As you can see, the values of k are on the console and the sum of these even numbers is 30. Now, let's look at another example. First, I will convert these codes to the comment line. You can declare and initialize two variables in the for loop. For example, let's create a for loop, for(int x = 0, int y = 1;). I'll create a condition using these variables, x <= 5 && y < 11.
In the increment part, x++, y++. Now, inside the loop, I'll print the x and y values. System.out.println("x = " + x); and I'll copy this line and paste it two times. I change the x to y, and this print method for separating each iteration. Okay. Let's run and see. As you can see, x and y are printed until the 5. After this step, the new value of x is 6 and the condition is false for the x variable. So, since the operator of the condition is the AND operator, the result value of this condition will be false and the loop will be terminated. Also, if you notice, the type of the x and y is the same. If you use a different data type here, you will get a compilation error. Don't forget this. And I will show you a nested for loop. We can create for loops one inside the other. Let's make an example. First, let's turn these codes to the comment line.
Okay. First, I will create the outer for loop. for(int a = 1; a < 4; a++). Inside this loop, I'll create another for loop. for(int b = 0; b <= 5; b++). Now, let's write the code here. I'll print the value of a and b using the print method. System.out.println("a = " +a); I'll copy this line and paste it below two times. I changed the a to b, and this print method for separating each iteration. Also, let's guess how many times the codes here will be run in total. The outer loop will execute three times because the starting value is one and the last value to be executed will be three. So, the codes in the outer block will be run three times in total. Every time the outer loop runs, the inner loop will run six times because the starting value is zero and the last value to be executed will be five. So, the codes in the inner block will be run 18 times in total.
Let's observe this in the console. For this, I'll create a new variable outside of the loops. int k = 0; Now, let's increase this value of k by 1 in the inner loop and print it to the console. I'll create another print method on top of the print methods here. System.out.println("number of loops = " + ++k); This increases the value of k and prints the updated value. Okay. Let's run the code and see. As you can see, the codes were run 18 times. I'll end the lesson by mentioning one last thing. Notice that we have always created a for loop here according to a condition and when the condition is not met, the loop ends. But we can also create an infinity or endless loop if we want.
While this is mostly the subject of the do-while loop, which we'll see later, you can also create infinity loops with the for loops. Let's do a quick example. Let's turn this into a comment line first. Now, let's create the loop. If you put double semicolon inside the parentheses, it means an infinite loop. For example, let's print java to the console. Now let's run our code. As you can see, the word 'java' will be printed to the console forever until we terminate the program. Here, we can also do this. We can have the compiler wait for a short time after each command is printed. This is out of the loops topic, but I want to show it to you anyway. You don't have to do this, I just want to show you.
We use the sleep method of the thread class in the java.lang package to delay the compiler. Here, I'm writing thread.sleep(); I should write the duration of the delay in milliseconds in the parentheses. In Java, 1 second equals 1,000 milliseconds. So, I'm typing 500 here to make the compiler wait for half a second. Also, this parameter must be of type long. That's why I also use the L suffix. Of course, as you can see, the compiler gives a compilation error because we have to put it in the try and catch block, which we'll learn later. Here, I choose the 'Surround with try-catch' option. As you can see, the compilation error has disappeared. Finally, I move the print method inside the try block. Now, let's run the application once again. And as you can see, this time, the word 'Java' is printed to the console at half second intervals. Yes friends, I guess that's enough for the for loop. Let's take a short break here. See you in the next lesson.
OAK Academy is made up of tech experts who have been in the sector for years and years and are deeply rooted in the tech world. They specialize in critical areas like cybersecurity, coding, IT, game development, app monetization, and mobile development.