Java中的字符串串联和自动装箱 [英] String Concatenation and Autoboxing in Java

查看:62
本文介绍了Java中的字符串串联和自动装箱的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当您将字符串与基本类型(例如int)连接时,会先自动装箱该值.

When you concatenate a String with a primitive such as int, does it autobox the value first.

例如.

String string = "Four" + 4;

如何在 Java 中将值转换为字符串?

How does it convert the value to a string in Java?

推荐答案

要查看Java编译器生成的内容,使用 javap -c 显示生成的实际字节码总是很有用的:

To see what the Java compiler produces it is always useful to use javap -c to show the actual bytecode produced:

例如以下Java代码:

For example the following Java code:

String s1 = "Four" + 4;
int i = 4;
String s2 = "Four" + i;

将产生以下字节码:

   0:   ldc     #2; //String Four4
   2:   astore_1
   3:   iconst_4
   4:   istore_2
   5:   new     #3; //class java/lang/StringBuilder
   8:   dup
   9:   invokespecial   #4; //Method java/lang/StringBuilder."<init>":()V
   12:  ldc     #5; //String Four
   14:  invokevirtual   #6; //Method java/lang/StringBuilder.append:(Ljava/lang/
String;)Ljava/lang/StringBuilder;
   17:  iload_2
   18:  invokevirtual   #7; //Method java/lang/StringBuilder.append:(I)Ljava/lan
g/StringBuilder;
   21:  invokevirtual   #8; //Method java/lang/StringBuilder.toString:()Ljava/la
ng/String;
   24:  astore_3
   25:  return

由此我们可以看到:

  • "Four" + 4 的情况下,Java编译器(我使用的是JDK 6)足够聪明,可以推断出这是一个常量,因此在运行时无需进行任何计算工作,因为字符串是在编译时连接的
  • 对于"Four" + i ,等效代码为 new StringBuilder().append("Four").append(i).toString()
  • 此处不涉及自动装箱,因为存在 StringBuilder.append(int)方法,根据文档,该方法使用的是
  • In the case of "Four" + 4, the Java compiler (I was using JDK 6) was clever enough to deduce that this is a constant, so there is no computational effort at runtime, as the string is concatenated at compile time
  • In the case of "Four" + i, the equivalent code is new StringBuilder().append("Four").append(i).toString()
  • Autoboxing is not involved here as there is an StringBuilder.append(int) method which according to the docs is using String.valueOf(int) to create the string representation of the integer.

这篇关于Java中的字符串串联和自动装箱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆