String concatenation in java

String concatenation using + operator::


String sunita="sunita"
String pndey="pandey";
String sunitapandey=sunita+pndey;

Under the covers what does a compiler do:


String sunitapandey=new StringBuilder(String.valueOf(sunita)).append(pndey).toString();

ByteCode for the same—-

0 ldc [16]
2 astore_1 [sunita]
3 ldc [18]
5 astore_2 [pndey]
6 new java.lang.StringBuilder [20]
9 dup
10 aload_1 [sunita]
11 invokestatic java.lang.String.valueOf(java.lang.Object) : java.lang.String [22]
14 invokespecial java.lang.StringBuilder(java.lang.String) [28]
17 aload_2 [pndey]
18 invokevirtual java.lang.StringBuilder.append(java.lang.String) : java.lang.StringBuilder [31]
21 invokevirtual java.lang.StringBuilder.toString() : java.lang.String [35]
24 astore_3 [sunitapandey]

//.toString method in Stringbuilder

@Override
public String toString() {
// Create a copy, don't share the array
return new String(value, 0, count);
}

the above concatenation will create a new StringBuilder with one char[] buffer with 16 size and at last .toString() method creates a new String object with a copy of StringBuilder buffer.

Suppose you are concatenating using + operator in a loop then imagine the number of temporary objects will be created.

so instead of doing like


String concat="";
for(int i=0;i<100;i++){
concat=concat+"abc";
}

one can efficiently do like

StringBuilder concat=new StringBuilder();
for(inti=0;i<100;i++){
concat.append("abc");
}
String con=concat.toString();

However ,one point to be noted here is , if i use “+” operator for a concatenation and if the result is resolved during compilation time itself then a new StringBuilder instance is not created , stringBuilder conversion is only done for those strings whose value is computed during runtime . Look at following example and their generated bytecode.


String grima="garima"+"pandey";

Bytecode for the same—
0 ldc [16]
2 astore_1 [grima]
3 return
Line numbers:
[pc: 0, line: 8]
[pc: 3, line: 9]
Local variable table:
[pc: 0, pc: 4] local: n index: 0 type: java.lang.String[]
[pc: 3, pc: 4] local: grima index: 1 type: java.lang.String

 Note–Whenever possible prefer .append(char[] str) or .append(char c) methods of StringBuilder over .append(String str) method of StringBuilder as its fast.

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s