string和int相加java_为什么java中string类型数据和int类型数据相加为string类型数据?...

参考java规范

因为+左右有一个String类的对象,而另一边不是,所以会将那个不是string的对象转换为string然后再连接。具体转换规则参考最下面。

Chapter 15. ExpressionsIf only one operand expression is of type String, then string conversion (§5.1.11) is performed on the other operand to produce a string at run time.

The result of string concatenation is a reference to a String object that is the concatenation of the two operand strings. The characters of the left-hand operand precede the characters of the right-hand operand in the newly created string.

渣翻如下

如果其中一个操作数表达式是String,那么对另一个操作数执行字符串转换,以在运行时产生一个字符串。

字符串连接的结果是对一个String对象的引用,该对象是两个操作数字符串的连接。左侧操作数的字符位于新创建的字符串中右侧操作数的字符之前。

An implementation may choose to perform conversion and concatenation in one step to avoid creating and then discarding an intermediate String object. To increase the performance of repeated string concatenation, a Java compiler may use the StringBuffer class or a similar technique to reduce the number of intermediate String objects that are created by evaluation of an expression

``````````````````````分割线`````````````````````````````````````

更加具体的每个类型的转换成字符串的规则

Chapter 5. Conversions and Contexts

5.1.11. String Conversion

Any type may be converted to type String by string conversion.

A value x of primitive type T is first converted to a reference value as if by giving it as an argument to an appropriate class instance creation expression (§15.9):

If T is boolean, then use new Boolean(x).

If T is char, then use new Character(x).

If T is byte, short, or int, then use new Integer(x).

If T is float, then use new Float(x).

If T is double, then use new Double(x).

This reference value is then converted to type String by string conversion.

Now only reference values need to be considered:If the reference is null, it is converted to the string "null" (four ASCII characters n, u, l, l).

Otherwise, the conversion is performed as if by an invocation of the toString method of the referenced object with no arguments; but if the result of invoking thetoString method is null, then the string "null" is used instead.

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值