0
 class Simple{ public static void main(String args[]){ String s="Sachin"+" Tendulkar"; System.out.println(s);//Sachin Tendulkar } } 

The compiler transforms this to:

 String s = (new StringBuilder()).append("Sachin").append(" Tendulkar").toString(); 

what is mean by last line?

3
  • 2
    Actually, it won't transform it to that at all. (At least not the Oracle compiler.) Commented Jul 8, 2014 at 19:18
  • With string literals I don't think the compiler has to use a StringBuilder. Now if you concatenated args into one String it would look something like that. It means the JVM will use a StringBuilder to perform String concatenation, since Java String(s) are immutable. Commented Jul 8, 2014 at 19:21
  • Like for your String taken :D Commented Jul 9, 2014 at 17:41

4 Answers 4

3

Java compiler will just concat this two string at compile time and it would result into following instructions

for code

public class StringConcatInspection { public static void main(String[] args) { String s = "Sachin" + " Tendulkar"; } } 

it would compile to

 Last modified Jul 9, 2014; size 473 bytes MD5 checksum 5238429068ccae4ec199f4af970ad46e Compiled from "StringConcatInspection.java" public class StringConcatInspection SourceFile: "StringConcatInspection.java" minor version: 0 major version: 52 flags: ACC_PUBLIC, ACC_SUPER Constant pool: #1 = Methodref #4.#20 // java/lang/Object."<init>":()V #2 = String #21 // Sachin Tendulkar #3 = Class #22 // StringConcatInspection #4 = Class #23 // java/lang/Object #5 = Utf8 <init> #6 = Utf8 ()V #7 = Utf8 Code #8 = Utf8 LineNumberTable #9 = Utf8 LocalVariableTable #10 = Utf8 this #11 = Utf8 LStringConcatInspection; #12 = Utf8 main #13 = Utf8 ([Ljava/lang/String;)V #14 = Utf8 args #15 = Utf8 [Ljava/lang/String; #16 = Utf8 s #17 = Utf8 Ljava/lang/String; #18 = Utf8 SourceFile #19 = Utf8 StringConcatInspection.java #20 = NameAndType #5:#6 // "<init>":()V #21 = Utf8 Sachin Tendulkar #22 = Utf8 StringConcatInspection #23 = Utf8 java/lang/Object { public StringConcatInspection(); flags: ACC_PUBLIC Code: stack=1, locals=1, args_size=1 0: aload_0 1: invokespecial #1 // Method java/lang/Object."<init>":()V 4: return LineNumberTable: line 4: 0 LocalVariableTable: Start Length Slot Name Signature 0 5 0 this LStringConcatInspection; public static void main(java.lang.String[]); flags: ACC_PUBLIC, ACC_STATIC Code: stack=1, locals=2, args_size=1 0: ldc #2 // String Sachin Tendulkar 2: astore_1 3: return LineNumberTable: line 6: 0 line 7: 3 LocalVariableTable: Start Length Slot Name Signature 0 4 0 args [Ljava/lang/String; 3 1 1 s Ljava/lang/String; } 

Compiler version: 1.7.0_60-ea

respect for sachin

Sign up to request clarification or add additional context in comments.

1 Comment

If you use javap -v, it will dump out the constant pool, and you can see how javac represents this in the constant pool (rather than just in the comments) next to the bytecodes.
1

If I understand correctly you're asking about how using StringBuilder differs from normal String concatenation (rather than some compiler/IDE optimisation).

Strings in Java are immutable, meaning that once they're created they cannot be modified. Therefore when you perform some operation on a given string - such as String.concat() or String.replaceAll() which look on first glance that they will alter the string's internal state - you are in fact creating a new string object which is derived from the original immutable object, and as such that has to be saved somewhere.

String example = "This is a test "; example = example.trim(); // "This is a test" 

Often such operations aren't terribly expensive but if you have to due a lot of String modification then using this approach can end up being very costly with all the object creation.

The alternative is to use a class like StringBuilder which represents mutable character sequence. With this class it is possible to modify the instance itself. So concatenation via the 'StringBuilder.append()' method is must cheaper in CPU/memory terms compared to 'String.concat()'. Of course, once you've finished constructing your StringBuilder you'll often want to get a normal String, hence its toString() method.

Another handy aspect of StringBuilder is that it uses method chaining so that its methods returns itself and that allows you to chain calls in one line.

StringBuilder b = new StringBuilder(); b.append("One"); b.append("Two"); b.append("Three").append("Four");

This can make certain things more readable, eg

StringBuilder sb = new StringBuilder(); sb.append(user.getLastName()).append(", ").append(user.getFirstName()); // Better than mixing String concatenation sb.append(user.getLastName() + ", " + user.getFirstName()); // Valid but defeats purpose of using StringBuilder 

Comments

0

When concatenating only string literals, the compiler should rewrite to just be the literals combined.

// source String s="Sachin"+" Tendulkar"; // compiler rewrite String s="Sachin Tendulkar"; 

However, if there is at least one non-constant, then my understanding is that a StringBuilder will be used to avoid creating temporary one-time-use objects that just make extra work for the garbage collector.

// source String s = "Sachin"+" Tendulkar" + title; // compiler rewrite (approximately) String s = (new StringBuilder("Sachin Tendulkar")).append(title).toString(); 

Whether it passes the literal to the constructor or uses .append on both strings is something I don't know. You can compile the code then try de-compiling it with JAD to find out.

Comments

0

Per the Java Language Specification, 3rd edition for Java SE 5, §15.28:

Compile-time constants of type String are always "interned" so as to share unique instances, using the method String.intern.

From the same document, §15.18.1:

The result [of the String Concatenation Operator +] is a reference to a String object (newly created, unless the expression is a compile-time constant expression (§15.28)) that is the concatenation of the two operand strings.

Emphasis mine.

So, the Java specification has been requiring, since at least Java 5, that constants formed by concatenating constants are interned strings, and thus are optimized to constants directly (without evaluating the concatenation at runtime).

Note too that because this is a requirement of the specification, all compliant implementations must implement this interning behaviour; it is not simply an optimization that the Sun/Oracle Java implementation chooses to use.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.