使用“+”时,整数如何以及为什么被类型转换为字符串?

How and why does an integer get typecast into String when using "+"?

当我执行此代码时,写入 + 会将我的整数转换为字符串。

public class Test {
public static void main(String...string){

    int m=9;
    int k=10;
    String s=new String(m +"");//automatic type conversion from int to string
    String j=m+"" +k;////automatic type conversion from int to string
    System.out.println(s+j);
    String s1=String.valueOf(m);
    System.out.println(s1);
}

}

我无法理解 + 在这里做什么,以及它是如何转换成字符串的。这是否与 = 运算符的从右到左优先级有关?

这与 = 运算符从右到左的优先级有关系吗?

回答:

而且它也与整数类型无关。 为什么 ?因为 JSL 说的是

String conversion applies only to an operand of the binary + operator which is not a String when the other operand is a String.

In this single special case, the non-String operand to the + is converted to a String (§5.1.11) and evaluation of the + operator proceeds as specified in §15.18.1.

所以即使你写任何其他类型的变量,它也会转换它考虑这个片段

public static void main(String...string){
    double u=9.0;
    System.out.println(u+"hi");


} 

它给了我输出

9.0hi

现在怎么样了?

对于我发布的代码片段 这是

编译代码的一部分
public static void main(java.lang.String...);
    flags: ACC_PUBLIC, ACC_STATIC, ACC_VARARGS
    Code:
      stack=5, locals=3, args_size=1
         0: ldc2_w        #16                 // double 9.0d
         3: dstore_1
         4: getstatic     #18                 // Field java/lang/System.out:Ljav
a/io/PrintStream;
         7: new           #24                 // class java/lang/StringBuilder
        10: dup
        11: dload_1
        12: invokestatic  #26                 // Method java/lang/String.valueOf
:(D)Ljava/lang/String;
        15: invokespecial #32                 // Method java/lang/StringBuilder.
"<init>":(Ljava/lang/String;)V
        18: ldc           #35                 // String hi
        20: invokevirtual #37                 // Method java/lang/StringBuilder.
append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
        23: invokevirtual #41                 // Method java/lang/StringBuilder.
toString:()Ljava/lang/String;
        26: invokevirtual #45                 // Method java/io/PrintStream.prin
tln:(Ljava/lang/String;)V

因此在内部它调用 valueOf() 方法将双精度或非字符串操作数转换为字符串,然后调用 append() 将其完全转换为字符串。 希望这对你有帮助:)

我想让答案更简单,所以我发布了这个。

'+' is the only operator in java that is overloaded for String type for string concatenation

因此,如果两个操作数中的任何一个是 String.. 整个操作会因连接而重载。

所以string+(any other datatype) = string. 因此,对于任何其他操作数,请将括号与字符串

一起使用

所以5+5+"" =55

(5+5)+"" = 10

注意:与从右到左的优先顺序无关