Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explanation about a Java statement

Tags:

java

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?

like image 770
monn Avatar asked May 11 '10 04:05

monn


2 Answers

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

int x = 1 + (+ (+ (+ (+ (+ (+ (+ (+ 2))))))));
like image 117
Matthew Flaschen Avatar answered Nov 15 '22 08:11

Matthew Flaschen


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

like image 29
YGL Avatar answered Nov 15 '22 09:11

YGL