The following code block
class Main {
public static void main(String[] args) {
System.out.println( + 1);
}
}
Compiles on java 1.8.
When this code is run 1
is printed.
Same with System.out.println(+ + 1);
However ++1
fails to compile.
+ + "str"
fails to compile.
+ + true
fails to compile.
So it looks like it is supported only for int, long and double.
What is the reason that this expression is valid for the above data types?
This is unary plus expression. It is here just to compliment unary minus expression.
Only numerical type suports it because for other types it doesn't make any sense.
++1
is not compiles because ++
is increment expression and requires variable or field as sub expression.
+1
is not an expression, it's an explicit way to say positive 1
. On the other hand, ++1
is a pre-increment expression on variable 1
, which doesn't exist, nor is it legal to have a variable name start with a digit. + + 1
is equivalent of +(+(1))
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With