整数作为字符串而不是整数执行?

时间:2014-09-26 13:58:00

标签: java

当我们进入for循环时,

for(int i =0; i< 10 ; i++)
{
   System.out.println(i + 1);
}

将执行1-10

但是,如果我将System.out.println改为让我们说一个函数passed,例如

for(int i=0;i<10;i++)
{
passed( "Row" + (i+1));
}

传递的地方是

public static void passed(String check) {

System.out.println(check + "Passed");
}

执行

01通过 11通过 21通过 31通过.... 41 51 61

等等

任何人都可以解释为什么它首先传递值并跳过数学?

3 个答案:

答案 0 :(得分:5)

System.out.println(i + 1);       --> println(int) called
System.out.println(check + "Passed"); --> println(String) is called.

java代码:

public static void main(String[] args) {
    int check = 0;
    System.out.println(check + "Passed"); //StringBuilder operation int + string concatenated as Strings then println is called.
    System.out.println(check + 5); // int + int concatenated as int, then println is called 
}

字节代码:

 0:   iconst_0
   1:   istore_1
   2:   getstatic       #16; //Field java/lang/System.out:Ljava/io/PrintStream;
   5:   new     #22; //class java/lang/StringBuilder
   8:   dup
   9:   iload_1       
   10:  invokestatic    #24; //Method java/lang/String.valueOf:(I)Ljava/lang/Str
ing;
    // use StringBuilder and invoke println()
   13:  invokespecial   #30; //Method java/lang/StringBuilder."<init>":(Ljava/la
ng/String;)V
   16:  ldc     #33; //String Passed
   18:  invokevirtual   #35; //Method java/lang/StringBuilder.append:(Ljava/lang
/String;)Ljava/lang/StringBuilder;  
   21:  invokevirtual   #39; //Method java/lang/StringBuilder.toString:()Ljava/l
ang/String;
   24:  invokevirtual   #43; //Method java/io/PrintStream.println:(Ljava/lang/St
ring;)V --> string println called
   27:  getstatic       #16; //Field java/lang/System.out:Ljava/io/PrintStream;
   30:  iload_1              // load value of check(int)
   31:  iconst_5           ---->  constant 5 
   32:  iadd               ----> add constant 5 and value of check and then invoke method
   33:  invokevirtual   #48; //Method java/io/PrintStream.println:(I)V --> integer println called
   36:  return

答案 1 :(得分:4)

Java在混合String和任何数字(intdouble,...)时应用特定规则:

System.out.println(1+1+""); //prints 2

然而

System.out.println(""+1+1);//prints 11

那是怎么回事?

Java将从右向左阅读并优先考虑String。因此,在第一种情况下,Java将在评估int + int = int之前评估int + String = String。但在第二个示例中,首先评估String + int = String,然后String + int = String

答案 2 :(得分:2)

当您直接调用System.out.println时,运行时间可以确定传递的值是int,并且应该在println之前执行添加(对于int } values)被执行。当您在一个函数中包含该调用时,该函数采用String参数并将int值传递给该函数,int值将被强制转换为String值调用passed,然后在执行println(用于String值)之前进行连接而不是添加。