Page 75 - iPlus_Ver_2.0_class_8
P. 75
The syntax of the if statement is as follows:
Start
if (< conditional expression >)
{
[statements]
}
Conditional False
For example, Expression
public class IfStatement
{
True
public static void main(int num)
Body of if
{
System.out.println("Entered number is: " + num);
if (num % 2 == 0)
Stop
{
System.out.println("The number is even"); Flowchart of 'if' statement
}
System.out.println("Statement outside the if statement");
}
}
Run the program twice for values of 22 and 7,
respectively. When you enter 22, the condition (22 %
2 == 0) returns true. So, the statement inside the body
of the if statement gets executed and the output will
appear as shown:
When you enter the value 7, then the output will
appear as shown:
Since the condition (7 % 2 == 0) returns false, the
statement inside the body of the if statement does
not get executed and only the statement outside the
if statement gets executed.
The if…else Statement
The if…else statement is used to execute either of the blocks of statements from if or else
statements. When the condition next to the if keyword evaluates to true, the statement(s)
inside the if block will be executed. Otherwise, the statement(s) inside the else block will be
executed.
73
Conditional, Looping and Jumping Statements in Java

