GeeCON Prague 2014*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Simple ??? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Simple ???" Watch "Simple ???" New topic
Author

Simple ???

Jui Mahajan
Ranch Hand

Joined: Jun 02, 2003
Posts: 62
int i = ++5;
Why is this declaration wrong ?


-----jui<br />scjp1.4
Corey McGlone
Ranch Hand

Joined: Dec 20, 2001
Posts: 3271
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


SCJP Tipline, etc.
 
 
subject: Simple ???