Java Conditional Statement: If- Else Statement

If- Else Statement 

To understand what an If- Else Statement is , let us first study what does the term Conditional Statement imply.

Conditional Statements  are a feature of programming languages that are used to make decisions based on the conditions. Conditional statements execute sequentially when there is no condition around the statements. If we apply some condition for a set of statements within the scope, the execution flow may change based on the result evaluated by the condition. This process is called decision making.

The ‘ If – Else Statement ‘ is an example of such conditional statements.

Understanding the concept

The ‘ If-Else ‘ statement is a functionality that executes a block of code only if a specified condition is true. If the condition is false, another block of code can be executed. It can be viewed as an extended version of ‘ If Statement ‘ .

  • The control initially falls into the if block.
  • The flow then jumps to the specified ‘ Condition ‘.
  • Now, The condition is tested.
    1. If Condition yields true, execute the part of code within the block
    2. If Condition yields false, the set of statements within the body of ‘else’ are executed.

For better understanding, the working of this flowchart has been given in the following image.

if else statement

Syntax of If- Else Statement

public class Main
{
public static void main(String[] args) {

if (condition)
{
// Executes this block if
// condition is true
}
else
{
// Executes this block if
// condition is false
}
}
}

Now that we have seen the syntax of the if- else statement, let us understand it further with the help of an example. 

We have a random number and a comparison factor. Now if the Condition specified with ‘ if ‘ is true the first block of codes is executed. Other wise the control fall out of the if block and jumps to else to execute the condition in case boolean results in a false value.

For this, the code using if-else statement will be:

Run
public class Main
{
	public static void main(String[] args) {
	    int x = 150;
	    if (x<100)
		{
                    System.out.println("Hey Prepster, This is the if block");
                }
            else
                {
                    System.out.println("Hey Prepster, This is the else block");
                }
	}
}

Output: 

Hey Prepster, This is the else block.