Java中的+=运算符

huangapple go评论90阅读模式
英文:

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;

是等价的,并且nulltrue会被隐式转换为字符串。这是因为在str + null中,编译器知道str是一个字符串,并将null转换为字符串。这是可能的,因为在Java中任何值都可以转换为字符串。按照同样的论证,编译器知道(str + null)是一个字符串,因此将true转换为字符串。

另一方面,

str += null + boolean;

等同于

str = str + (null + boolean);

因此,首先会对null + boolean进行求值。由于类型nullboolean的操作符+未定义,因此会生成编译器错误。

英文:

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 Strings. 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.

huangapple
  • 本文由 发表于 2020年9月22日 23:31:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/64013000.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定