What happens if you remove the space between the + and ++ operators?

EDIT 1

DISCLAIMER: I know that +++ not an operator, but the + and ++ operators are without a space. I also know that there is no reason to use this; this question is just out of curiosity.


So, I am interested to know if a space is required between + and ++var in Java.

Here is my test code:

 int i = 0; System.out.println(i); i = i +++i; System.out.println(i); 

This produces:

 0 1 

which works as I would expect, just as if there was a space between the first and second + .

Then I tried it with string concatenation:

 String s1 = "s " + ++i; System.out.println(s1); // String s2 = "s " +++i; 

This produces:

 s 2 

But if the third line is uncommented, the code does not compile with an error:

 Problem3.java:13: unexpected type required: variable found : value String s2 = "s " +++i; ^ Problem3.java:13: operator + cannot be applied to <any>,int String s2 = "s " +++i; ^ 

What causes a difference in behavior between string concatenation and adding an integer?


EDIT 2

As discussed in the question of continuing Abhijit , the rule that people talked about (first you need to parse the larger token ++, to the shorter token ++) was discussed in this presentation , where it seems to be called the Munchy Munchy rule.

+7
source share
4 answers

The compiler generates the longest tokens when analyzing the source, therefore, when it is encountered with +++ , it accepts it as ++ + .

So the code

 a +++ b 

Will always be the same as

 (a++) + b 
+5
source

No operator +++ . You have a postfix ++ statement followed by an infix + statement. This is a compilation error because postfix ++ can only be applied to a variable, and "s " not a variable.

Since you really mean the infix + operator followed by the ++ prefix, you need to put space between the operators.

Actually, you should do this at any time. +++ is a crime against readability !!!

+13
source

The triple plus is not the operator itself; it combines two operators:

What the triple plus does is:

a +++ 1 == a ++ + 1;

What you are trying to do is a ++ line, which is undefined.

Never use +++ without spaces in the code; hardly anyone will know what he is doing (without consulting online). Moreover, after a week or so, you will not know what this is actually doing.

+2
source

+++ is not in itself.

i = i +++i; leads to the value of pre-increment i , and then adds it to the value of i and stores it in i .

Using String + does not mean adding, so you are trying to concatenate a string and an integer.

+1
source

All Articles