Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Simple ???

 
Jui Mahajan
Ranch Hand
Posts: 62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
int i = ++5;
Why is this declaration wrong ?
 
Corey McGlone
Ranch Hand
Posts: 3271
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
From the JLS, §15.14.1 Postfix Increment Operator ++:

A variable that is declared final cannot be incremented, because when an access of a final variable is used as an expression, the result is a value, not a variable. Thus, it cannot be used as the operand of a postfix increment operator.

You're attempting to perform an increment operation on a constant value, 5. This is roughly equivalent to performing an increment operation to a final variable.
In this case, the JVM would have to evaluate 5++. In that case, it would use the value 5 as the initial value and then update the variable 5. That doesn't make any sense.
In short, Java expects a variable in this position - a constant value is not allowed. You can get that from the error message, as well:

Test.java:5: unexpected type
required: variable
found : value
int i = ++5;

1 error

I hope that helps,
Corey
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic