While Loop
Start course
Difficulty
Beginner
Duration
3h 15m
Students
55
Ratings
4/5
starstarstarstarstar-border
Description

In this course, we look at control flow statements in the Java programming language. 

Learning Objectives

  • Decision-making statements
  • Looping statements
  • Branching statements 

Intended Audience

  • 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

Prerequisites

  • No prior knowledge is required about the Java programming language.
  • Basic computer knowledge
Transcript

Hi there. In this video, we'll talk about another loop. The while loop. In the while loop, the controlling variable is defined previously. Condition is evaluated first and if it returns true, then the statement in the loop body are executed. Generally, the loop body contains an update value for the variable being processed for the next iteration. If the condition returns false, the control comes out of the loop and jumps to the next statement after the while loop. Let's make some examples with the while loop. In exercise project, right-click on the loop package and select "New," "Class." Specify the class name as WhileLoop and select the checkbox for the main method. Let's declare a variable i type of int and the initial value is five. Our loop condition is i > 1. 

We'll use the print method to display numbers. So, I write s.out.println(i). We need to update the variable  i. So, we will decrease the value of i by one. Before running the app, let's examine this while loop. In the beginning the value i is five. The condition is true because five is greater than one. So, the loop body will execute and the first number, we will see in the console will be five and the decrement operator will evaluate and the new value of i will be four and now the first iteration is finished. It begins the second iteration. The new value of i is four and four is greater than one, so the condition is true. The loop body will evaluate again like that and the loop will continue until the value of i is one. If i is equal to one, the condition will be false because one is not greater than one. So, the loop will not evaluate this time and the compiler will continue after the loop body. Now let's run the code and see the result. You see the numbers 5, 4, 3 and 2. After four iterations, i will be one. Then our condition  i is greater than one is evaluated to false and the while loop terminates. Let's write a program to calculate the factorial of the first five numbers with a while loop. I'll turn these codes to the comment line. First of all, let's talk about factorial. Maybe there are those who forgot about it or did not know it at all. The factorial of a number is obtained by multiplying the numbers from itself to one. For example, when calculating the factorial of three, we multiply 3, 2, and 1. And we can say that the factorial of three is six.

Or when calculating the factorial of five we multiply the numbers 5,4,3,2 and 1. And we can say that the factorial of five is 120. I think the factorial is understood. Now we can start coding. Let's declare two variables: 1st k with the initial value one and second fact with the initial value one. Let's start while loop with a condition k <= 5. In the loop, we assign fact multiply k  to the variable fact with a multiply and assignment operator. Let's print the value of k and the fact variable by using the print method. And lastly, we will increase the value of k by one. Let's run the code. As you can see, the factorial of one is one, factorial of two is two, factorial of three is six, factorial of four is 24, and factorial of five is 120. Now let's take another example. I'll convert these codes to the comment line. And now I'll create two int variables; int a = 5, int b = 10. 

Now let's write a while loop like that, while( a < 4). I will increase the value of a by one and I'll decrease the value of b by one. And after the loop, I'll write a code with a turn array operator like that; int c = a > b  ? a--  : b++. And lastly, let's print the last value of these variables using the println method method. System.out.println("a="+a). I'll copy this line and paste it below twice. This will be b and this will be c. Before running the code, let's examine it. In the while condition, we'll check the variable a. So, the initial value of a is five and five is not less than four. So, the condition is false. And the loop body will never evaluate. So, it will jump to this line. In this line, we use the turn array operator. In the turn array operator if the condition is true, the first statement will be executed. If the condition is false, the second statement will be executed. So, the value of a is still five and the value of b is still 10. Since the five is not greater than 10, the condition will be false and the second statement will be executed. And here, we used the b++ increment operator. 

So, firstly, the value of b will assign to the c variable and then the value of b will be increased by one. As a result, the value of a will never change and it is five. The new value of b will be 11 and the value of c will be 10. Now we can run the code and see. As you can see, the value of a is five, b is 11, and c is 10. As a result, if the condition is false the loop body will never execute. So, what happens if the condition we define in while is false at the beginning? Let's look at this now. For example, if I write while(false), as you can see, the compiler gives a compilation error because the condition is false at the beginning and the code you will write in the while block will not never execute. So, the codes you will write here are unreachable to the compiler. Pay attention to that. Also, I want to talk to you about infinite loops. An infinite loop means a loop that never ends. It can also be used as an endless loop. Now let's write infinite while loop examples. 

If we start a while loop with a condition true, this is an infinite while loop because this condition is always true and will not be never false. For this reason, this loop continues forever. Let's look at another example. For instance, let's create a variable type int and named d, and the initial value is 100. If we start while loop with a condition like this, d ==100. This is also an infinite while loop. But if we activate the previous infinite loop, we'll get an error in this case. Let's remove the comment line now. As you can see, we're getting an error because the previous while loop is an infinite loop and it will never end. Therefore the code we write after an endless loop will never work. Pay attention to that, this is important. If we convert the first loop to the comment line as you can see, the compilation error disappeared. 

So, where and when can we use the infinite loop? Let's look at this now. In the while loops, the loop continues until the desired condition is met. The loop terminates when the desired condition is met. Notice that in the examples we've done so far, we've set a condition and continued the loop until the condition is met using increment or decrement operations at the end of the loop. But here, we are determined how long the loop would take. So, what should we do if we don't know how long the cycle will last? Let me explain this with an example. For example, you'll develop a number guess application. In other words, the computer will generate a random number in the range you specify, and you will ask the user to guess this number. If the user cannot know the number randomly generated by the computer, he is constantly asked to enter a new guess. 

So, as long as the user does not guess correctly, an infinite loop will continue. If the user guesses the randomly generated number, the loop will terminate. As a result, if we want some code to run continuously, we can use infinite loops. Now, let's do a simple number guess application and understand the infinite loop better. First, we need to generate a random number. For this, we use the class named random from the java.util package in Java. I'll create an object from the random class. I write, random, and select the random class in java.util package, and random = new Random. Now let's generate a random number using the random object. Here, I write random.next. When you type .next, as you can see, a lot of options appear. So, we can generate random numbers of type integer, double or float. Here, I choose the next int method because I will generate the int numbers. Finally, I must specify the range of the number to be generated. 

For this example, let's generate a random number between 0 and 100. For this, I write 100 here, thus, the smallest number to be randomly generated will be 0 and the largest number will be 99. Now, let's transfer this randomly generated number to a variable. I write, int randomNumber = at the beginning of this code. Thus, a random number between 0 and 100 will be generated and assigned to the variable random number. Now, we have a randomly generated number. Now, let's take the user's guess. For this, I will use the scanner class again. Scanner input = new Scanner, in parentheses, I write (System.in). Now, I'll give a message that informs the user using the println method. I write, ("Please enter a number"). Now, let's create our infinite while loop. After typing the while, we must write an expression in parentheses that will always be true. For example, we can write that  2 > 1 or we can write true. 

It's enough that the expression you write here is a correct expression. You can write anything you want, for now, I'm writing that 2 > 1. Now, let's take the user's guess and pass it to a variable in the while loop. I will do this in the while loop. If we do this before the loop, the loop continues forever. But when we get the user's guess here, every time the loop returns to the beginning it will wait for the response from the user. So here, I write int userGuess = input.nextInt. We can now evaluate the user's guess using the if else statement. If the user guess is equal to the randomNumber, let's message the user, ("Congrats... You know the number in my mind"); Of course, if the user's guess is correct, the condition will be satisfied and the loop will have to end. So, how do we end the loop in this case?

For this, it's enough to write the break keyword here. As soon as you type the break keyword, your loop will end. Now, let's create the other conditions. Here, I will use the else if statement. If the user's guess is less than the randomly generated number, we can tell the user to increase his guess. Finally, in the else block we can tell the user to decrease his guess because the last condition is that the user's guess is greater than the randomly generated number. Yes, so we created the infinite loop. This loop will continue until the user guesses correctly. Now, let's run and test our code. As you can see, there's an expression that tells us to enter a number in the console. Currently, a value between 0 and 100 is generated and passed to the variable number. As we enter our guess, our guess will be compared with the variable number. I type 50 as the first guess and press 'Enter.' 

As you can see, we could not know the randomly generated number and we need to increase our guess. As a second guess, I type 60 and press 'Enter.' Unfortunately, I still could not know, I need to increase my guess again. Now I'm entering 70, I need to increase it again. I'm entering 80, I need to increase it again. I'm entering 90, so this time it says, decrease your number. So, the randomly generated number is between 80 and 90. I will enter 85 this time, I need to increase it again. I'm entering 87, I need to increase it again. I'm entering 88, I need to increase it again. I'm entering 89, and correct guess. As you can see guys, the loop will continue until we guess correct. However, when we guess correctly, the loop will end. This is what we call an infinite loop. I think the concepts of while loop and infinite loop are understood. Let's take a short break here. In our next lesson, we'll learn about the do-while loop. See you in the next lesson.

 

About the Author
Students
1922
Courses
64
Learning Paths
4

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.

Covered Topics