Java. Arithmetic operations.tokenized. How?
Who can 开发者_如何转开发explain or give a good reference for understanding this example:
int a=1;
int b=2;
System.out.println(a---b); //correct
System.out.println(a- -b); //correct
System.out.println(a--b); //wrong
thanks.
The expression a---b
is not (as you perhaps expected) parsed as a-(-(-b))
but rather as (a--) - b
.
This example illustrates it:
int a = 0;
int b = 0;
System.out.println(a---b); // prints 0
System.out.println(a); // prints -1
With this behaviour in mind, a--b
is parsed as (a--)b
which is obviously an error.
When you put a space between the minuses, a- -b
it's no longer parsed as the --
operator, but as a binary and unary minus: a - (-b)
.
Note that you can write a- - -b
which is interpreted as a-(-(-b))
.
So why is it interpreted like this? Well @EJP gave an excellent comment on another answer. In the JLS, section 3.2 you can read the following:
The longest possible translation is used at each step, even if the result does not ultimately make a correct program while another lexical translation would. Thus the input characters
a--b
are tokenized (§3.5) asa
,--
,b
, which is not part of any grammatically correct program, even though the tokenizationa
,-
,-
,b
could be part of a grammatically correct program.
The Java Language Specification.
-
and --
are unary operators. Therefore can't be used with two operands. That's why
System.out.println(a--b);
is wrong. --
is applied to a
, so the new value of a
is 0
. If you add one more -
, then the value of a
decremented by 1
will be subtracted by the value of b
yielding -2
精彩评论