Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is `+ 1` a valid expression in Java? [duplicate]

Tags:

java

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?

like image 981
Prathik Rajendran M Avatar asked Jan 27 '23 22:01

Prathik Rajendran M


2 Answers

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.

like image 189
talex Avatar answered Feb 06 '23 03:02

talex


+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)).

like image 32
Jai Avatar answered Feb 06 '23 03:02

Jai