go to previous page   go to home page   go to next page hear noise highlighting

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?


go to previous page   go to home page   go to next page