Pages

Saturday, December 25, 2021

Decision Statements - if-else statement

Concept

The if-else statement will execute one group of statements if its boolean expression is true, or another group if its boolean expression is false.

Syntax

Here is the general format:

if (BooleanExpression)
statement or block
else
statement or block

Logic


How if-else statement works?

Like the if statement, a boolean expression is evaluated. If the expression is true, a statement or block of statements is executed. If the expression is false, however, statements within else part is executed.

Example (IfElseDemo.java)

class IfElseDemo {
    public static void main(String args[])
    {
        int i = 20;
  
        if (i < 15)
            System.out.println("i is smaller than 15");
        else
            System.out.println("i is greater than 15");
  
        System.out.println("Outside if-else block");
    }
}

Output
i is greater than 15
Outside if-else block


No comments:

Post a Comment