Why does this Java code with “+ +” compile?

后端 未结 8 854
梦毁少年i
梦毁少年i 2020-12-10 10:25

I\'m curious why this simple program could be compiled by java using IntelliJ (Java 7).

public class Main {
    public static void main(String[] args)
    {
         


        
8条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-10 11:13

    ++ and + are both operators. They are elements of the language. Technically they can be referred to as tokens. + + is not a single token in Java and is broken down into two individual tokens during the parsing stages of compilation.

    + can exist in two forms: (i) as a unary operator; for example +10 (which is essentially a no-op which only adds to the confusion) or (ii) as a binary operator (meaning it acts on two thing) to add two terms; for example 10 + 10.

    Since they have an intrinsic value, you can also regard 10 and +10 as both being expressions. You should also note that the unary + has a very high operator precedence so it will bind tightly to the expression immediately after it.

    So what is happening in your code is the the compiler is binding the + just to the left of the expression 10 to produce another expression with value 10. Then that binds the second leftmost unary + to produce, yet again, 10.

    In summary: without the space, ++ is a single token. With any space between them, the two + act as two unary operators.

提交回复
热议问题