Skip to main content
ICT
Lesson A3 - Primitive Data Types
 
Main   Previous Next
 

I. Increment and Decrement Operators page 11 of 14

  1. Incrementing or decrementing by one is a common task in programs. This task can be accomplished by the statements:

    n = n + 1;    or   n += 1;

  2. Java also provides a unary operator called an increment operator, ++.

  3. The statement n = n + 1 can be rewritten as ++n. The following statements are equivalent:

    n = n + 1; ++n;
    sum = sum + 1; ++sum;
  4. Java also provides for a decrement operator, --, which decrements a value by one. The following are equivalent statements:

    n = n - 1; --n;
    sum = sum - 1; --sum;
  5. The increment and decrement operators can be written as either a prefix or postfix unary operator. If the ++ is placed before the variable it is called a pre-increment operator (++number), but it can follow after the variable (number++), which is called a post-increment operator. The following three statements have the same effect:

    ++number;    number++;    number = number + 1;

  6. Before looking at the difference between prefix and postfix unary operators, it is important to remember Java operators solve problems and often return values. Just as the assignment operator (=) returns a value, the ++ and -- operators return values. Consider the following code fragments:

  7. The statement b = ++a uses the pre-increment operator. It increments the value of a and returns the new value of a.

  8. The statement b = a++ uses the post-increment operator. It returns the value of a and then increments a by 1.

  9. The precedence and associativity of the unary increment and decrement operators is the same as the unary - operator.

 

Main   Previous Next
Contact
 © ICT 2006, All Rights Reserved.