Java_String_字符串“+”的问题

来源:互联网 发布:优酷播放量 淘宝 编辑:程序博客网 时间:2024/05/21 03:19

例:

package deep;public class Client {    public static void main(String[] args) {        String str1 = 1 + 2 + " apples";        String str2 = "apples:" + 1 + 2;        System.out.println(str1);        System.out.println(str2);    }}

运行结果:
3 apples
apples:12

为什么两次输出的苹果数量不一致?这源于Java对加号的处理机制:在使用加号进行计算的表达式中,只要遇到String字符串,,String字符串前面的计算后转换为字符串拼接,String字符串后面的数据也被转变成String类型进行拼接,再看例子:

package deep;public class Client {    public static void main(String[] args) {        String str1 = 1 + 2 + " apples" + 3 + 4;        String str2 = "apples:" + 1 + 2;        System.out.println(str1);        System.out.println(str2);    }}

运行结果:
3 apples34
apples:12

对于str2字符串,由于第一个参与运算的是String类型,加上1后的结果是“apples:1”,这仍然是一个字符串,然后再与2相加,其结果还是一个字符串,也就是“apples:12”。这说明如果第一个参数是String,则后续的所有计算都会转变成String类型。

0 0
原创粉丝点击