Java:空间在编译中有所作为? [英] Java : space makes a difference in compilation?
问题描述
我正在编写一个程序(有点像Piglatin ...),在其中我无意中错过了语句中的变量:
I was making a program (A Piglatin sort of...), in which I unintentionally missed a variable in the statement:
String a = "R"++'a';
它实际上应该是 String a ="R" + text +'a';
.编译器产生一个错误.但是,当我做到这一点时:
It should actually have been String a = "R"+text+'a';
. The compiler produced an error. But, when I made it:
String a = "R"+ +'a';
程序已编译.
我想知道,为什么Java不在乎是否在某些语句中放置空格,例如: String a ="ABCD";
与字符串a ="ABCD";
I am wondering why putting a space made the difference even though Java does not care whether you put a space or not in certain statements, like : String a="ABCD";
is the same as String a = "ABCD";
有人可以解释这种行为吗?
Can someone please explain this behavior?
推荐答案
++
本身就是 operator (先递增或后递增).
++
is an operator in its own right (pre or post increment).
将其放在字符串和char文字之间在语法上无效.
Putting it between a string and a char literal is not syntactically valid.
但是使用"R" + +'a'
,第二个 +
将绑定到字符常量 a
并将其用作一元加号运算符(此运算符具有很高的优先级).这不是不是的禁止操作:在Java中,它具有将 a
的 type 提升为 int
.这种类型的提升表示输出将是 R97
而不是 Ra
(97是 a
的ASCII码).其余的 +
充当字符串连接器.
But with "R"+ +'a'
, the second +
will bind to the char literal a
and will act as the unary plus operator (this operator has a very high precedence). This is not a no-op: in Java it has the effect of promoting the type of a
to an int
. This type promotion means that the output will be R97
rather than Ra
(97 is the ASCII number for a
). The remaining +
acts as the string concatenator.
这篇关于Java:空间在编译中有所作为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!