问题
EDIT 1
DISCLAIMER: I know that +++
is not really an operator but the +
and ++
operators without a space. I also know that there's no reason to use this; this question is just out of curiosity.
So, I'm interested to see if the space between +
and ++var
is required in Java.
Here is my test code:
int i = 0;
System.out.println(i);
i = i +++i;
System.out.println(i);
This prints out:
0
1
which works as I would expect, just as if there were 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 prints out:
s 2
But if the third line is uncommented, the code does not compile, with the 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's causing the difference in behavior between string concatenation and integer addition?
EDIT 2
As discussed in Abhijit's follow-up question, the rule that people have mentioned (the larger token ++ be parsed first, before the shorter token ++) is discussed in this presentation where it appears to be called the Munchy Munchy rule.
回答1:
Compiler generates longest possible tokens when parsing source, so when it encounters +++, it takes it as ++ +.
So the code of
a +++ b
Will always be same as
(a++) + b
回答2:
There is no +++
operator. What you have there is a postfix ++
operator followed by an infix +
operator. That is a compilation error because postfix ++
can only be applied to a variable, and "s "
isn't a variable.
Since you really mean an infix +
operator followed by a prefix ++
operator, you need to put the space in between the operators.
Actually, you should do it ANYWAY. +++
is a crime against readability!!!
回答3:
The triple plus is not an operator itself, it is two operators combined:
What the triple plus acutually does is:
a+++1 == a++ + 1;
What you are trying to do is ++ a String, which is undefined.
Never ever use +++ without spaces in your code; hardly anyone will know what it does (without consulting web). Moreover, after a week or so, you will not know what it actually does yourself.
回答4:
+++
isn't an operator by itself.
i = i +++i;
results in a pre-increment value of i
, then adding it to the value of i
and storing it in i
.
With the String, +
doesn't mean addition, so you're attempting to concatenate the string and the integer together.
来源:https://stackoverflow.com/questions/15378392/what-happens-if-you-remove-the-space-between-the-and-operators