Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams Why doesn't the post increment operator work on a method that returns an int? (11 answers)
Closed 5 years ago .
if (questions.size() >= answers.size()) { answers.forEach(answer -> { if (questions.contains(answer)) this.answer.setPoints((this.answer.getPoints())++); // Variable expected ^

The error I encountered is:

unexpected type
required: variable
found: value

What is wrong with the statement?

this.answer.setPoints((this.answer.getPoints())++);
                If postincrement works the same in Java as it does in C (quite likely) then even if the syntax was correct, you'd still end up with the same value ...
– Jongware
                Mar 22, 2016 at 21:40

The ++ operator only makes sense when applied to a declared variable.

This operator will add one to an integer, long, etc. and save the result to the same variable in-place.

If there is no declared variable, there is nowhere to save the result, which is why the compiler complains.

One way to allow use of the ++ operator in this situation would be (not the most concise code, but to illustrate the point):

int myVariable = this.answer.getPoints();
myVariable++;
this.answer.setPoints(myVariable);

this.answer.getPoints() will return a value, and you can't use increment ++ or decrement -- on that. You can only use it on variables.

If you want to add 1 to it, you can do it as:

this.answer.setPoints((this.answer.getPoints())+1);

++ will increment a variable with 1, but since this.answer.getPoints() will return a value and its not a defined variable, it won't be able to store the incremented value.

Think of it like doing: this.answer.getPoints() = this.answer.getPoints() + 1, where would the incremented value be stored?

@AndrewTobilko because you can't modify the return value of a method, and ++ modifies the variable it's used on? – Louis Wasserman Mar 22, 2016 at 21:43

The first part of this (this.answer.getPoints()) creates an rvalue: effectively, an anonymous variable that lasts almost no time.

The second part ++ increments that anonymous variable after it is passed into setPoints().

Then, the anonymous variable (now incremented) is thrown away.

The compiler/IDE knows that you're doing something that will never be used (incrementing a temporary value), and is flagging it.