Win a copy of Create an Uber Clone in 7 Days: Build a real world full stack mobile app in Java this week in the Android forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Simple ???  RSS feed

 
Ranch Hand
Posts: 62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
int i = ++5;
Why is this declaration wrong ?
 
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
 
To do a great right, do a little wrong - shakepeare. twisted little ad:
Why should you try IntelliJ IDEA ?
https://coderanch.com/wiki/696337/IntelliJ-IDEA
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!