Menu
Topics Index
...
`

Block of code for if - Java Example Program


Block of code for if
class IfCodeBlock
{
    public static void main(String arg[])
    {
        short marks = 95;
        
        if( marks > 90 )
        {
            System.out.println("Excellent"); // LINE A
            System.out.println("Scholarship Granted"); // LINE B
        }
    
    }
}
OUTPUT

Excellent
Scholarship granted

DESCRIPTION

Here we want to print Excellent and Scholarship granted when marks are greater than 90. If we do not include these two statements in the code block i.e. in curly braces { }, then Scholarship granted will be printed whether or not marks are greater than 90. Since if considers only the first statement after the condition. Even indenting will not help, since java is free-form language and does not give importance to spaces, tabs etc.

THINGS TO TRY
  • Remove curly braces enclosing LINE A and LINE B and compile it. Change marks to 100, 90 and 80 and see the various outputs.
  • Include LINE B inside one more block i.e. place open curly brace { just before System in LINE B and close curly brace } just after ; and before comment // LINE B. If it is placed after // LINE B it will be considered as a comment and throws a compilation error.

© meritcampus 2019

All Rights Reserved.

Open In App