Prefix Increment Operator

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
go to previous page   go to home page   hear noise   go to next page

Answer:

Yes.

Prefix Increment Operator

The increment operator ++ can be put in front of a variable. When this is done, it is a prefix operator. When it is put behind a variable it is a postfix operator. Both ways increment the variable. However:

++counter means increment the value before using it.
 
counter++ means increment the value after using it.

When the increment operator is used as part of an arithmetic expression you must distinguish between prefix and postfix operators.

int sum = 0;
int counter = 10;

sum = ++counter ;

System.out.println("sum: "+ sum " + counter: " + counter );

This program fragment will print:

sum: 11  counter: 11 

This fragment requires careful inspection:

  • The ++ operator is now a prefix operator.
  • Now, counter is incremented before the value it holds is used.
  • The assignment statement is executed in two steps:
    1. Evaluate the expression on the right of the =
      • the value is 11 (because counter is incremented before use.)
    2. Assign the value to the variable on the left of the =
      • sum gets 11.
  • The next statement writes out: sum: 11 counter: 11

The Java AP Examination does not test students on using the prefix operator for any purpose (not even to increment an isolated variable).

QUESTION 6:

Inspect the following code:

int x = 99;
int y = 10;

y = ++x ; // prefix increment operator

System.out.println("x: " + x + "  y: " + y );

What does this fragment write out?