3

Wasn't sure exactly how to word the question, but I noticed something strange while constructing a date. I found that if I construct a date like this

new Date(+ 1)

it compiled just fine, and so did

new Date(+ + + 1)

If I execute the following, the output is 1

public static void main(String[] args) {
    int x = 1;
    System.out.println(+ + + + x);
}

Can anyone explain what it is that the JVM thinks I am doing?

one stevy boi
  • 577
  • 6
  • 24

2 Answers2

12

It's the unary operator (+). You can always add a + to a numeral and that will give you the positive value of the number.

Because you're spacing the tokens out in such a fashion, the lexer is not interpreting anything here as incrementation, so you're adding four unary (+) operations to a value 1.

Makoto
  • 104,088
  • 27
  • 192
  • 230
4

It's treating it like this:

System.out.println(+ (+ (+ (+ x))));

This is no different than

System.out.println(- (- (- (- x))));
clabe45
  • 2,354
  • 16
  • 27