How many Strings does this create?
String test(String text) {
return "string 1 " +
text + " string 2 " +
"string 3";
}
No new String calls are present here, the only one that exists is in StringBuilder.toString, so
1
java.lang.String test(java.lang.String);
Code:
Stack=3, Locals=2, Args_size=2
0: new #16; //class java/lang/StringBuilder
3: dup
4: ldc #18; //String string 1
6: invokespecial #20; //Method java/lang/StringBuilder."<init>":(Ljava/lang/String;)V
9: aload_1
10: invokevirtual #23; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
13: ldc #27; //String string 2
15: invokevirtual #23; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
18: ldc #29; //String string 3
20: invokevirtual #23; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
23: invokevirtual #31; //Method java/lang/StringBuilder.toString:()Ljava/lang/String;
26: areturn
This is pretty easy to answer by compiling the code, then inspecting the bytecode with javap -c
. In this particular case, the compiler should generate code like
String result = new StringBuilder("string1").
append(text).append("string2").append("string3").toString();
so depending on how you look at it, you might say only one, or if you're one of those people who likes to count literals as being "created" when they're used, you could say four.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With