What happens when you literally concatenate a number into a String object? [duplicate]
Solution 1:
Bytecode of
int i = 10;
System.out.println("" + i);
will look like this
GETSTATIC java/lang/System.out : Ljava/io/PrintStream;
NEW java/lang/StringBuilder
DUP
INVOKESPECIAL java/lang/StringBuilder.<init> ()V
LDC ""
INVOKEVIRTUAL java/lang/StringBuilder.append (Ljava/lang/String;)Ljava/lang/StringBuilder;
ILOAD 1
INVOKEVIRTUAL java/lang/StringBuilder.append (I)Ljava/lang/StringBuilder;
INVOKEVIRTUAL java/lang/StringBuilder.toString ()Ljava/lang/String;
INVOKEVIRTUAL java/io/PrintStream.println (Ljava/lang/String;)V
As you can see new StringBuilder
is created and append(int)
method is invoked.
System.out.println(10)
case even simpler. There is several overloaded method whit name println
and one of them accept int
as parameter.
Solution 2:
Your two examples are not related.
In the first example
int x = 1234;
String y = "Some random String " + x;
Here basically following code is generated internally.
new StringBuilder("Some random String ").append(x)
In the 2nd Example
int x = 1234;
System.out.println(x);
There are so many overloaded methods of the PrintStream System.out:
println(boolean x)
println(char x)
println(int x)
println(long x)
println(float x)
println(double x)
println(char x[])
println(String x)
println(Object x)
here println(int x) is invoked
Solution 3:
String is a Class in Java. int is a primitive type.
You can't force cast a primitive type to an Object.
Operand "+" is a special operand, for example:
public class TestSimplePlus
{
public static void main(String[] args)
{
String s = "abc";
String ss = "ok" + s + "xyz" + 5;
System.out.println(ss);
}
}
let's take a look at the decompilation code:
package string;
import java.io.PrintStream;
public class TestSimplePlus
{
public TestSimplePlus()
{
// 0 0:aload_0
// 1 1:invokespecial #8 <Method void Object()>
// 2 4:return
}
public static void main(String args[])
{
String s = "abc";
// 0 0:ldc1 #16 <String "abc">
// 1 2:astore_1
String ss = (new StringBuilder("ok")).append(s).append("xyz").append(5).toString();
// 2 3:new #18 <Class StringBuilder>
// 3 6:dup
// 4 7:ldc1 #20 <String "ok">
// 5 9:invokespecial #22 <Method void StringBuilder(String)>
// 6 12:aload_1
// 7 13:invokevirtual #25 <Method StringBuilder StringBuilder.append(String)>
// 8 16:ldc1 #29 <String "xyz">
// 9 18:invokevirtual #25 <Method StringBuilder StringBuilder.append(String)>
// 10 21:iconst_5
// 11 22:invokevirtual #31 <Method StringBuilder StringBuilder.append(int)>
// 12 25:invokevirtual #34 <Method String StringBuilder.toString()>
// 13 28:astore_2
System.out.println(ss);
// 14 29:getstatic #38 <Field PrintStream System.out>
// 15 32:aload_2
// 16 33:invokevirtual #44 <Method void PrintStream.println(String)>
// 17 36:return
}
}
As we can see, "+" operand is to call StringBuilder.append() while at least one of the parameters is string
Hope you get it!