Use ++ with Caution

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:

value: 11 result: 20

Use ++ with Caution

The example program fragment:

int value = 10 ;
int result = 0 ;

result = value++ * 2 ;

System.out.println("value: " + value + "  result: " + result );

is equivalent to this program fragment:

int value = 10 ;
int result = 0 ;

result = value * 2 ;
value  = value + 1 ;

System.out.println("value: " + value + "  result: " + result );

The second fragment is one statement longer, but easier to understand. Use the increment operator only where it makes a program clearer. Don't use it to avoid extra typing. The increment operator can make some very confusing code if you are not careful.

The increment operator must be applied to a variable. The following is incorrect:

int x = 15;
int result;

result = (x * 3 + 2)++  ;   // Wrong!

QUESTION 5:

(Thought question:) Would it sometimes be useful to increment the value in a variable before using it?