Menu
Topics Index
...
`


Control Statements > Selection Statements >
Siva Nookala - 12 Apr 2016
if condition in Java is a conditional branch statement, which can be used to route program execution through different paths.

if condition in Java can be used to execute a block of code only when a condition is true, if the condition is false we can execute a different block of code.

    if(condition)
    {
        statement1;
    }
    else
    {
        statement2;
    }
As shown above, if the condition is true then, statement1 is executed. If it is false, statement2 is executed.
Print PassFail Result
class PrintPassFail
{
    public static void main(String arg[])
    {
        int marks = 62;
        if(marks > 35)            // LINE A
        {
            System.out.println("Pass");     // LINE B
        }
        else
        {
            System.out.println("Fail");     // LINE C
        }
    
    }
}
OUTPUT

Pass

DESCRIPTION

Here marks are initialized to 62. Then the condition marks > 35 will become true, so LINE B is executed which prints Pass. If the marks are only 20, instead of 62, then the condition is false, causing LINE C to execute, printing Fail.

THINGS TO TRY
  • Try the below code.
    int a = 10;
    int b = 5;
    if (a > b)
        System.out.println("a is greater than b");
    else
        System.out.println("b is greate than a");
    The output should be a is greater than b, since the value of a is greater than b.
  • Try the below code.
    int a = 10;
    int b = 9;
    if (a > b)
        System.out.println("a is greater than b");
    System.out.println("I am not in if block");
    The output should be as shown.
    a is greater than b
    I am not in if block

    Only the first statement below if condition comes into if block.
  • It is not necessary to have an else block for every if condition . An if can exist without else. In this scenario if block is executed only if the condition is true, otherwise nothing is executed.
  • It is not necessary to put the code in flower brackets { }, if only one statement needs to be executed. If there are more than one statement, then we need to put them in flower brackets { }. This is valid even for else block. But writing if-else conditions without flower brackets is not suggested as it causes confusion, if the code is not formatted properly. Please refer Expressions, Statement, Line & Block In Java to understand the difference between expression, statement, line and blocks of code.

Dependent Topics : Control Statements In Java  Expressions, Statement, Line & Block In Java 

0
Wrong
Score more than 2 points

© meritcampus 2016 - 2017

All Rights Reserved.