I am so suprise when I using two Java increment operators at the same time.
Please check below codes..
public class Testing {
public static void main(String... str) {
int prefix = 0, postfix = 0, both = 0;
// Testing prefix
System.out.println(prefix);
System.out.println(++prefix);
System.out.println(prefix);
// Testing postfix
System.out.println(postfix);
System.out.println(postfix++);
System.out.println(postfix);
// mixing both prefix and postfix (I think this should be fine)
// System.out.println(++ both ++);
}
}
Why I can't use as ++ both ++
? Could anyone explain me please ? Thanks..
The result of ++x
or x++
is categorized as a value, not a variable - and both operators will only work on variables.
For example, from section 15.14.2 of the JLS:
A postfix expression followed by a ++ operator is a postfix increment expression.
PostIncrementExpression: PostfixExpression ++
The result of the postfix expression must be a variable of a type that is convertible (ยง5.1.8) to a numeric type, or a compile-time error occurs.
The type of the postfix increment expression is the type of the variable. The result of the postfix increment expression is not a variable, but a value.
(Pretty much identical language is used for the PrefixIncrementExpression
in 15.14.3.)
See more on this question at Stackoverflow