Before we learn the while
and do...while
loops, we will discuss the if
condition in this section. In a Java program, when the if
conditional statement is used, the statement in the if
block is executed only if the condition is satisfied. Otherwise the statement from else
block is run. Also this execution is just takes place once. In a for
loop, a variable is initiated and the loop runs till the condition is satisfied.
However, in the if
case, it will not keep on looping. It will just go inside the loop once the if
condition is satisfied; otherwise, it will go into the else
block. So, control will execute the statements present in this else
block, as shown in the following screenshot:
Output of the if...else condition as per the code
But all this happens only once, unlike the for
loop, where a condition is satisfied until it goes back and executes.
Let's take a look at the following example:
if(5>2) { System.out.println("success"); } else { ...