String concatenation and autoboxing in Java

When you combine String with a primitive such as int, does this have an autobox value.

ex.

String string = "Four" + 4;

How to convert a value to a string in Java ?

+5
source share
3 answers

To find out what the Java compiler produces, it is always useful to use javap -cto show the resulting bytecode:

For example, the following Java code:

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

will create the following bytecode:

   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

From here you can see:

  • In the case "Four" + 4, the Java compiler (I used JDK 6) was smart enough to infer that it is a constant, so there is no computational effort at runtime since the string is concatenated at compile time
  • "Four" + i new StringBuilder().append("Four").append(i).toString()
  • , StringBuilder.append(int), , , String.valueOf(int) .
+5

java- StringBuilder 1 append(). :

22  invokespecial java.lang.StringBuilder(java.lang.String) [40]
...   
29  invokevirtual java.lang.StringBuilder.append(int) : java.lang.StringBuilder [47]
32  invokevirtual java.lang.StringBuilder.toString() : java.lang.String [51]

, , toString(): "Four" + new Integer(4).toString() - , .


(1) , int literal "Four4". :

 0  ldc <String "Four4"> [19]
+4

According to http://jcp.org/aboutJava/communityprocess/jsr/tiger/autoboxing.html , autoboxing is performed on a primitive type whenever a link type is needed (for example, the Integer class in this case)

Thus, int will be converted to Integer, then the integer toString () object is called and its result is added to the previous line.

0
source

All Articles