Page 79 - TP_iPlus_V2.1_Class8
P. 79

The syntax of the if…else statement is as follows:
                                                                                Start
                 if (< conditional expression >)
                 {
                        [statements]

                 }
                                                                             Conditional     False
                                                                                                       Body of else
                 else                                                        Expression
                 {
                        [statements]                                               True
                 }
                                                                              Body of if
                 For example:
                 public class IfElseStatement

                 {
                                                                                Stop
                      public static void main(int num)
                      {                                                       Flowchart of if ....else statement

                           System.out.println("Entered number is: " + num);
                           if (num % 2 == 0)

                           {
                           System.out.println("The number is even");
                           }

                           else
                           {

                           System.out.println("The number is odd");
                           }
                           System.out.println("Statement outside the if...else statement");

                      }
                 }

                 As you did in the previous example, run the program
                 twice for the values of 22 and 7, respectively. When
                 you enter 22, the condition (22 % 2 == 0) returns true.
                 So, the output will appear as shown:


                                                                                                Output
                                                             When you enter the value 7, then the output will
                                                             appear as shown:

                                                             Because the condition (7% 2 == 0) in the if statement
                                                             returns false, control is transferred to the statements

                                Output                       in the else block.


                                                                                                                  77
                                                                 Conditional, Looping and Jump Statements in Java
   74   75   76   77   78   79   80   81   82   83   84