Register Now

Login

Lost Password

Enter your email to reset your password.

BY Author

Java – Control Statements

Java Programming Language Control Statement

The statements those who control the order of execution of a program are known as control statements.

The if-else control statement

The if-else statement is used to choose & execute any one action among two.

Syntax

if(condition)
{
    // group of programming statements
}
else
{
    // group of programming statements
}

Braces in the if-else and other control statements are optional if we used only one statement for every action, as shown below:

if(condition)
    single_statement;
else
    single_statement;

The syntax without braces can be used only when there is a need to execute a single statement for every action.

The syntax with braces can be used to execute a single statement as well as group of statements for every action.

It is good to use braces to avoid confusions because curly braces help to distinguish statements as a separate & a single group from other.

If the condition present inside the parentheses is true, if-block is executed. After execution of if-block, program control skips else-block and jumps directly to the statements after else-block.

If the condition inside the parenthesis is false, else-block is executed by skipping if-block.

Flowchart

Java Programming Language if-else Flowchart

Working

Java Programming Language if-else Working

Example No. 1

class IfElseDemo1 
{
    public static void main(String args[])
    {
        int i;
        i = 5;
        if(i<10)
        {
            System.out.println("Inside if block");
        }
        else
        {
            System.out.println("Inside else block");
        }
        System.out.println("After if-else block");
    }
}

Output

Inside if block
After if-else block

In the above program value of i is less than 10. Therefore condition becomes true and program control enters into if-block and executes the statement inside it.

Example No. 2

class IfElseDemo2 
{
    public static void main(String args[])
    {
        int i;
        i = 15;
        if(i<10)
        {
            System.out.println("Inside if block");
        }
        else
        {
            System.out.println("Inside else block");
        }
        System.out.println("After if-else block");
    }
}

Output

Inside else block
After if-else block

In the above program value of i is greater than 10. Therefore condition becomes false and program control enters directly into else-block by skipping if-block and executes the statement inside else-block.

Leave a reply