Search code examples
javaunary-operator

How does different spacing affect the unary operator?


Can anyone explain me how different spacing affects the unary operator?

int i = 1;
int j = i+ + +i; // this will print j=2
int k = i++ +i; // this will print k=3
int l = i+++i; // this will print l=3
int m = i++++i; // compile time error

.


Solution

  • First, let's separate this into three separate cases which can't interact:

    int i = 1;
    System.out.println(i+ + +i); // 2
    
    int j = 1;
    System.out.println(j++ +j); // 3
    
    int k = 1;
    System.out.println(k+++k); // 3
    

    Now let's rewrite them using brackets:

    int i = 1;
    System.out.println(i + (+(+i)));
    
    int j = 1;
    System.out.println((j++) + j);
    
    int k = 1;
    System.out.println((k++) + k);
    

    First operation

    Here we can't be using the prefix or postfix ++ operators, as we don't have a token of ++ anywhere. Instead, we have a binary + operator and two unary + operators.

    Second operation

    This one's simple: it's pretty much as it reads, a postfix ++ operator followed by a binary + operator (not the unary + operator that +j might otherwise imply).

    Third operation

    The final line is parsed as (k++) + k rather than k + (++k). Both will actually give the same answer in this situation, but we can prove which is which by using two different variables instead:

    int k1 = 1;
    int k2 = 1;
    System.out.println(k1+++k2); // Prints 2
    System.out.println(k1); // Prints 2
    System.out.println(k2); // Prints 1
    

    As you can see, it's k1 that's been incremented rather than k2.

    The reason that k+++k is parsed as tokens of k, ++, +, k is due to section 3.2 of the JLS, which includes:

    The longest possible translation is used at each step, even if the result does not ultimately make a correct program while another lexical translation would.

    Fourth operation (compile failure)

    The same "longest possible translation" rule parses i++++i as i, ++ ,++, i which isn't a valid expression (because the result of the ++ operation is a value, not a variable).