if..else Statement


An if statement can be followed by an optional else statement, which executes when the Boolean expression is false.

Syntax:

if(condition)
{
   //Statements which will be executed if the condition is true
}
else
{
   //Statements which will be executed if the condition is false
}

  • Here if the condition is true, the code which is written inside the curly brackets { } of the if block will be executed.  

  • If the condition is false, the code which is written inside the curly brackets { } of the else block will be executed.
Example:
  • We can take a look on a program which will display a message “Success” if a particular value is greater than 5.
  • If this value is not greater than 5, it will display a message “Failure”.
  • It then displays a message “Executed successfully” and complete its execution.
/*
* FileName :  IfElseStatementDemo1.java
*/
public class IfElseStatementDemo1
{
    public static void main(String args[])
    {
        //Declaring a variable "test" and initializing it with a value 10
        int test=10;

        //Checking if "test" is greater than 5
        if(test>5)
        {
            //This block will be executed only if "test" is greater than 5
            System.out.println("Success");
        }
        else
        {
            //This block will be executed only if "test" is not greater than 5
            System.out.println("Failure");

        }

        //The if else blocks ends.
        System.out.println("Executed successfully");
    }
}

Output:

Success
Executed successfully;

  • This program outputs the message “Success” because the declared variable “test” has a value 10 which is greater than 5.
  • If the value of “test” was lesser than or equal to 5, the message “Failure” would have been displayed instead of “Success”.

Popular posts from this blog

Naming Conventions

if..else..if Loader

Nested if..else Statement