Page 77 - iprime_V2.2_class8
P. 77

The syntax of the 'if' statement is as follows:
                                                                                                Start
                 if (< conditional expression >)
                 {
                        [statements]
                                                                                             Conditional     False
                 }                                                                           Expression

                 For example:
                                                                                                    True
                 public class IfStatement

                 {                                                                            Body of if
                       public static void main(int num)

                       {
                                                                                                 End
                              System.out.println("Entered number is: "
                                                                                            Flowchart of 'if' Statement
                            + 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
                                                                                         Output When Input Is 22
                 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                                                    Output When Input Is 7


                 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.


                                                                  Conditional, Loop and Jump Statements in Java    75
   72   73   74   75   76   77   78   79   80   81   82