Page 338 - Computer_Science_F5
P. 338

// Next for prefix when x is reset to 10
                         x = 10;
                         // Using ++x                                                              Chapter Five: Object oriented programming with Java
                         int y2 = ++x;
          FOR ONLINE READING ONLY
                         System.out.println(“Answer after ++x: “ + y2); // Output: 11
                         System.out.println(“Incremented value of x: “ + x);    // Output: 11
                     }
                 }


                Output:
































                                       Figure 5.7: Increment and decrement

              When an increment or decrement operator comes before its operand, Java executes
              the operation before retrieving the operand’s value for the remaining expression.
              However, if the operator comes after its operand, Java fetches the operand’s value
              first and then performs the increment or decrement operation. For example in the
              first case (x++) , y1 is set to 10 while still x becomes 11. For the second case, (++x),
              y2 is set to 11 when x will still be 11.

              To see more about how the program works in Java operators, write the following
              Program Example 5.6 in any editor then compile and run the program in JDK using
              cmd.exe:

                                                    329
               Student’s Book  Form Five



     Computer Science Form 5.indd   329                                                     23/07/2024   12:34
   333   334   335   336   337   338   339   340   341   342   343