if...else condition

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
{
System.out.println("fail");
}

The following screenshot displays those errors:

Quick fixes drop down with suggestions to correct the code error

The first error is to remove the including condition, which can be ignored. On running the preceding program, you will see the output as success because the condition 5 greater than 2 that went inside is true:

Output displays success as per the code

If we change the condition and make 5 less than 2, making the condition false, it will skip to the else block and execute the statement present in else.

code to receive fail as the output

This time the output should be fail, as shown in the following screenshot:

Output displays success as per the code

This is how the if condition works.

Note that if there is only a single line in your block, then you can get rid of these braces, because it eventually assumes that the next line will be executed if the condition is true. This means if you just have a single line in your block, then you can get rid of the braces. But if you want to have more than one statement, if your condition is true, then make sure you write that in braces to avoid conflict. If you do not specify the braces, it will still print as success, as shown in the following screenshot:

Output displays success after modifying the code

Here, 5 is greater than 2. On running this, the program will run without braces. 

Now, on adding one more statement, say "second step", it throws an error, as shown in the following screenshot:

Error is flagged with a cross mark besides the line number, showing syntax error

Notice the syntax error on the token in the preceding screenshot. Either you should keep a brace or you should avoid this step. To get rid of that, we will just keep the entire block in the brace. In this way, the error goes away.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.48.135