开发者

Explanation about a Java statement

开发者 https://www.devze.com 2022-12-29 16:55 出处:网络
public static void main(String[] args) { int x = 1 + + + + + + + + + 2; System.out.println(x); } I ca开发者_开发百科n compile above method. Is there any explanation about the allowed multiple \"+\"
public static void main(String[] args) {
    int x = 1 + + + + + + + + + 2;
    System.out.println(x);
}

I ca开发者_开发百科n compile above method. Is there any explanation about the allowed multiple "+" operator?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号