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
}
}
}
DESCRIPTIONHere 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.
- 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.
2-min video about if condition in Java