Monday, January 18, 2010

String vs StringBuffer vs StringBuilder

Difference between String , StringBuffer and StringBuilder :


Let us first write one sample program using Java String:

Program:

class Demo{
public static void main(String args[]){
String s ="shyamala";
System.out.println("java"+s);
}
}


compile the above program and run u get the output as : javashyamala
then after this see the description about the bytecode using

cmd/> javap -c Demo

Compiled from "Demo.java"
class Demo extends java.lang.Object{
Demo();
Code:
0: aload_0
1: invokespecial #1; //Method java/lang/Object."":()V
4: return
public static void main(java.lang.String[]);
Code:
0: ldc #2; //String shyamala
2: astore_1
3: getstatic #3; //Field java/lang/System.out:Ljava/io/PrintStream;
6: new #4; //class java/lang/StringBuilder
9: dup
10: invokespecial #5; //Method java/lang/StringBuilder."":()V
13: ldc #6; //String java
15: invokevirtual #7; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
18: aload_1
19: invokevirtual #7; //Method java/lang/StringBuilder.append:(Ljava/lang/ String;)Ljava/lang/StringBuilder;
22: invokevirtual #8; //Method java/lang/StringBuilder.toString:()Ljava/lang/String;
25: invokevirtual #9; //Method java/io/PrintStream.println:(Ljava/lang/String;)V
28: return
}

observe the highlighted lines in the above bytecode where by inbuilt it is using StringBuilder class when it is creating string.When we are using "+" operator with the strings it invokes append method of stringBuilder.

GC will be invoked manier times in case of String as once the string literal is not used again it should invoke Garbagecollector.


Other options include with javap:

javap -c Demo
to print Java1 Virtual Machine bytecodes,

javap -l Demo
to display line number and local variable tables (you need to compile perf.java with -g for this to work), and

javap -p Demo
to print private methods and fields in addition to the public ones.
javap is a handy tool for digging beneath the surface to find out what's really going on in a .class file.


About string :
1)Immutable class
2) Not thread safe

the performance is higher as it is using StringBuilder but when it is required frequent appending to a string better to go for stringBuffer which is mutable as well thread safety class.

StringBuilder
1) Mutable
2)Not threadsafety

StringBuffer:
1)Mutable
2)Threadsafety

http://java.sun.com/developer/TechTips/1998/tt0120.html#tip1
Thats it any queries get back to me!!!