Experiment 14: Increment and Decrement Expressions

There are other assignments that occur so commonly, Java provides special operators for them, too. For example, if x and y are integer variables, then in place of having to write

x = x + 1;


y = y - 1;

Java allows us to write




The operators ++ and -- are called the increment and decrement operators, respectively. Each has two forms: the prefix form and the postfix form. When used as a statement:




the prefix and postfix forms are equivalent. Their difference is in the value produced by the operator. Below is an experiment designed to help determine the difference:

   int x1,

   Keyboard theKeyboard = new Keyboard();

   x1 = theKeyboard.readInt();            // input a value
   x2 = x1;              // make a copy
   prefixResult = ++x1;  // save result of prefix form
   postfixResult = x2++; // save result of postfix form
                         // display results
   theScreen.println(" x1: " + x1 + " x2: " + x2);
   theScreen.println(" prefix produced: " + prefixResult 
        + " postfix produced: " + postfixResult );

Take a few moments to study this experiment, until you understand what it is doing. Then add it to Express.java and use it to experiment with a variety of input values. Report your findings in the space below:

The decrement operator (--) works in exactly the same fashion, except that it subtracts 1 from its operand, instead of adding one.

You should now be aware of the Java shortcuts for the increment and decrement operations, and also understand how the prefix version of each operator differs from the postfix version.

Back to the Exercise List

Back to the Table of Contents

Back to the Introduction

Copyright 2000 by Prentice Hall. All rights reserved.