monn
monn

Reputation: 737

Explanation about a Java statement

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?

Upvotes: 6

Views: 208

Answers (6)

jillionbug2fix
jillionbug2fix

Reputation: 52

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

Upvotes: 0

Matthew Flaschen
Matthew Flaschen

Reputation: 284786

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

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

Upvotes: 11

catchmeifyoutry
catchmeifyoutry

Reputation: 7349

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

Upvotes: 2

giri
giri

Reputation: 27199

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

Upvotes: 0

vodkhang
vodkhang

Reputation: 18741

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

Upvotes: 0

YGL
YGL

Reputation: 5570

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

Upvotes: 3

Related Questions