Showing posts with label String buffer. Show all posts
Showing posts with label String buffer. Show all posts

Friday, 29 August 2014

What is the difference between STRINGBUFFER and STRING?

What is the difference between STRINGBUFFER and STRING?
String object is immutable. i.e , the value stored in the String object cannot be changed. For e.g.
String myString = “Hello”;
myString = myString + ” Guest”;
System.out.println("myString " + myString);
When you run System.out on myString  the output will be “Hello Guest”. Although we made use of the same object (myString), internally a new object was created in the process because -  String is an immutable class in java . That’s a performance issue.
StringBuffer/StringBuilder objects are  mutable   StringBuffer/StringBuilder objects are mutable i.e. we can make changes to the value stored in the object. This means is that string operations such as append would be more efficient if performed using StringBuffer/StringBuilder objects than String objects.
String str = “Be Happy With Your Salary.''
str += “Because Increments are a myth";
StringBuffer strbuf = new StringBuffer();
strbuf.append(str);
System.out.println(strbuf);
The Output of the code snippet would be: Be Happy With Your Salary. Because Increments are a myth. But here the difference is that only one  object of stringbuffer is created in the example. That improves space complexity of the program.