Home » Java » Explanation about a Java statement

Explanation about a Java statement

Posted by: admin December 28, 2021 Leave a comment

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

I can compile above method. Is there any explanation about the allowed multiple “+” operator?

Answers:

It’s addition, then the unary plus operator repeated. It’s equivalent to the following:

int x = 1 + (+ (+ (+ (+ (+ (+ (+ (+ 2))))))));

###

The reason is that + can act as a unary operator, similar to how – can be the negation operator. You are just chaining a bunch of unary operators together (with one final binary addition).

###

it evaluates to 1 + (+ ... (+(+(+2))) ... ) = 1 + 2 = 3

###

I think they treated all those plus as the same one +. Because the output is 3, so there is no magic here at all

###

you do not get any exceptions, it works fine. You will get output 3.

###

Its because though syntactically it may seem wrong use of ‘+’ but there is this unary operation is repeating itself.