英文:
Java += operator
问题
我理解的是,x+=1 相当于 x=x+1,但为什么在字符串中不起作用?
String str = "";
str = str + null + true; // 没问题
str += null + true; // 错误信息:对于参数类型 null、boolean,未定义运算符 +
英文:
as far as I understand x+=1 works as x=x+1, but why it doesn't work in String?
String str = "";
str = str + null + true; // fine
str += null + true; // Error message: The operator + is undefined for the argument type(s) null, boolean
答案1
得分: 5
在Java中,表达式从左到右进行求值。因此,
str = str + null + true;
与
str = (str + null) + true;
是等价的,并且null
和true
会被隐式转换为字符串。这是因为在str + null
中,编译器知道str
是一个字符串,并将null
转换为字符串。这是可能的,因为在Java中任何值都可以转换为字符串。按照同样的论证,编译器知道(str + null)
是一个字符串,因此将true
转换为字符串。
另一方面,
str += null + boolean;
等同于
str = str + (null + boolean);
因此,首先会对null + boolean
进行求值。由于类型null
、boolean
的操作符+
未定义,因此会生成编译器错误。
英文:
In Java, expression are evaluated from left to right. Thus
str = str + null + true;
is the same as
str = (str + null) + true;
and null
and true
are implicitly converted to String
s. This works because in str + null
, the compiler knows that str
is a String
and converts null
to a String
. This is possible because every value can be converted to a String
in Java. By the same line of argumentation, the compiler knows that (str + null)
is a String
and thus coverts true
to a String
.
On the other hand,
str += null + boolean;
is equivalent to
str = str + (null + boolean);
hence, null + boolean
is evaluated first. Since the operator +
is not defined for types null, boolean
, a compiler-error is generated.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论