Page 77 - Trackpad_ipro 4.1_Class8
P. 77
The if Statement
The if statement is the most basic conditional statement in Java that allows us to test a condition
before executing a block of statements. If the provided conditional expression returns true, the
statements specified in the body of the 'if' statement are executed.
The syntax of the 'if' statement is as follows:
if (< conditional expression >) Start
{
[statements]
}
Conditional False
Expression
For example:
public class IfStatement
True
{
Body of if
public static void main(int num)
{
System.out.println("Entered number is: " Stop
+ num);
if (num % 2 == 0)
{
System.out.println("The number is even");
}
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 appears as shown:
When you enter the value 7, then the output appears 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.
Conditional, Looping and Jumping Statements in Java 75

