4

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?

Prathik Rajendran M
  • 1,152
  • 8
  • 21
  • What do you expect to happen by doing `++1`? – Nicholas K Jan 03 '19 at 05:54
  • `++1` failing is fine since there is no variable to increment and store, however I am wondering why `+ + 1` compiles. – Prathik Rajendran M Jan 03 '19 at 05:55
  • BTW I stumbled upon this while adding string with a character, that is "test" + + '}' is a valid expression and I got to thinking why its allowed. – Prathik Rajendran M Jan 03 '19 at 05:56
  • `1` is a v+ `1` that can also be written like `+1` and similarly -ve can be written as `-1`, (but not `+1` is an expression but just `1` is a literal) for negation en expression result you can put `-` minus in front of expression as `-exp` => to negate result of expression `+1` you can write `-+1` ...now this should give you an idea why `++1` is valid and also `+-1` or `-----1` is valid – Grijesh Chauhan Jan 03 '19 at 05:58
  • @GrijeshChauhan i think you have misspelled your comment in the end b/w invalid and valid. '....why ++1 is valid and also +-1 or -----1 is valid ' . – Jabongg Jan 03 '19 at 07:37

3 Answers3

6

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.

talex
  • 17,973
  • 3
  • 29
  • 66
1

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

Jai
  • 8,165
  • 2
  • 21
  • 52
1

Because + separated by space is treated as unary operator

For example

- - 5 => -(-5) => 5

Similarly

+ + 5 => +(+5) => 5
Doc
  • 10,831
  • 3
  • 39
  • 63