What is the difference between String and String Buffer? [duplicate] - java

What is the difference between String and StringBuffer in Java?
Is there a maximum size for String?

String is used to manipulate character strings that cannot be changed (read-only and immutable).
StringBuffer is used to represent characters that can be modified.
Performance wise, StringBuffer is faster when performing concatenations. This is because when you concatenate a String, you are creating a new object (internally) every time since String is immutable.
You can also use StringBuilder which is similar to StringBuffer except it is not synchronized. The maximum size for either of these is Integer.MAX_VALUE (231 - 1 = 2,147,483,647) or maximum heap size divided by 2 (see How many characters can a Java String have?).
More information here.

A String is immutable, i.e. when it's created, it can never change.
A StringBuffer (or its non-synchronized cousin StringBuilder) is used when you need to construct a string piece by piece without the performance overhead of constructing lots of little Strings along the way.
The maximum length for both is Integer.MAX_VALUE, because they are stored internally as arrays, and Java arrays only have an int for their length pseudo-field.
The performance improvement between Strings and StringBuffers for multiple concatenation is quite significant. If you run the following test code, you will see the difference. On my ancient laptop with Java 6, I get these results:
Concat with String took: 1781ms
Concat with StringBuffer took: 0ms
public class Concat
{
public static String concatWithString()
{
String t = "Cat";
for (int i=0; i<10000; i++)
{
t = t + "Dog";
}
return t;
}
public static String concatWithStringBuffer()
{
StringBuffer sb = new StringBuffer("Cat");
for (int i=0; i<10000; i++)
{
sb.append("Dog");
}
return sb.toString();
}
public static void main(String[] args)
{
long start = System.currentTimeMillis();
concatWithString();
System.out.println("Concat with String took: " + (System.currentTimeMillis() - start) + "ms");
start = System.currentTimeMillis();
concatWithStringBuffer();
System.out.println("Concat with StringBuffer took: " + (System.currentTimeMillis() - start) + "ms");
}
}

String StringBuffer
Immutable Mutable
String s=new String("karthik"); StringBuffer sb=new StringBuffer("karthik")
s.concat("reddy"); sb.append("reddy");
System.out.println(s); System.out.println(sb);
O/P:karthik O/P:karthikreddy
--->once we created a String object ---->once we created a StringBuffer object
we can't perform any changes in the existing we can perform any changes in the existing
object.If we are trying to perform any object.It is nothing but mutablity of
changes with those changes a new object of a StrongBuffer object
will be created.It is nothing but Immutability
of a String object
Use String--->If you require immutabilty
Use StringBuffer---->If you require mutable + threadsafety
Use StringBuilder--->If you require mutable + with out threadsafety
String s=new String("karthik");
--->here 2 objects will be created one is heap and the other is in stringconstantpool(scp) and s is always pointing to heap object
String s="karthik";
--->In this case only one object will be created in scp and s is always pointing to that object only

String is an immutable class. This means that once you instantiate an instance of a string like so:
String str1 = "hello";
The object in memory cannot be altered. Instead you will have to create a new instance, copy the old String and append whatever else as in this example:
String str1 = "hello";
str1 = str1 + " world!";
What is really happening hear is that we are NOT updating the existing str1 object... we are reallocating new memory all together, copying the "hello" data and appending " world!" to the end, then settings the str1 reference to point to this new memory. So it really looks more like this under the hood:
String str1 = "hello";
String str2 = str1 + " world!";
str1 = str2;
So it follows that this "copy + paste and move stuff around in memory" process can be very expensive if done repitively especially recursively.
When you are in that situation of having to do things over and over utilize StringBuilder. It is mutable and can append strings to the end of the current one because it's back by an [growing array] (not 100% if that is the actual data structure, could be a list).

From the API:
A thread-safe, mutable sequence of characters. A string buffer is like a String, but can be modified. At any point in time it contains some particular sequence of characters, but the length and content of the sequence can be changed through certain method calls.

A StringBuffer is used to create a single string from many strings, e.g. when you want to append parts of a String in a loop.
You should use a StringBuilder instead of a StringBuffer when you have only a single Thread accessing the StringBuffer, since the StringBuilder is not synchronized and thus faster.
AFAIK there is no upper limit for String size in Java as a language, but the JVMs probably have an upper limit.

I found interest answer for compare performance String vs StringBuffer by Reggie Hutcherso
Source: http://www.javaworld.com/javaworld/jw-03-2000/jw-0324-javaperf.html
Java provides the StringBuffer and String classes, and the String class is used to manipulate character strings that cannot be changed. Simply stated, objects of type String are read only and immutable. The StringBuffer class is used to represent characters that can be modified.
The significant performance difference between these two classes is that StringBuffer is faster than String when performing simple concatenations. In String manipulation code, character strings are routinely concatenated. Using the String class, concatenations are typically performed as follows:
String str = new String ("Stanford ");
str += "Lost!!";
If you were to use StringBuffer to perform the same concatenation, you would need code that looks like this:
StringBuffer str = new StringBuffer ("Stanford ");
str.append("Lost!!");
Developers usually assume that the first example above is more efficient because they think that the second example, which uses the append method for concatenation, is more costly than the first example, which uses the + operator to concatenate two String objects.
The + operator appears innocent, but the code generated produces some surprises. Using a StringBuffer for concatenation can in fact produce code that is significantly faster than using a String. To discover why this is the case, we must examine the generated bytecode from our two examples. The bytecode for the example using String looks like this:
0 new #7 <Class java.lang.String>
3 dup
4 ldc #2 <String "Stanford ">
6 invokespecial #12 <Method java.lang.String(java.lang.String)>
9 astore_1
10 new #8 <Class java.lang.StringBuffer>
13 dup
14 aload_1
15 invokestatic #23 <Method java.lang.String valueOf(java.lang.Object)>
18 invokespecial #13 <Method java.lang.StringBuffer(java.lang.String)>
21 ldc #1 <String "Lost!!">
23 invokevirtual #15 <Method java.lang.StringBuffer append(java.lang.String)>
26 invokevirtual #22 <Method java.lang.String toString()>
29 astore_1
The bytecode at locations 0 through 9 is executed for the first line of code, namely:
String str = new String("Stanford ");
Then, the bytecode at location 10 through 29 is executed for the concatenation:
str += "Lost!!";
Things get interesting here. The bytecode generated for the concatenation creates a StringBuffer object, then invokes its append method: the temporary StringBuffer object is created at location 10, and its append method is called at location 23. Because the String class is immutable, a StringBuffer must be used for concatenation.
After the concatenation is performed on the StringBuffer object, it must be converted back into a String. This is done with the call to the toString method at location 26. This method creates a new String object from the temporary StringBuffer object. The creation of this temporary StringBuffer object and its subsequent conversion back into a String object are very expensive.
In summary, the two lines of code above result in the creation of three objects:
A String object at location 0
A StringBuffer object at location 10
A String object at location 26
Now, let's look at the bytecode generated for the example using StringBuffer:
0 new #8 <Class java.lang.StringBuffer>
3 dup
4 ldc #2 <String "Stanford ">
6 invokespecial #13 <Method java.lang.StringBuffer(java.lang.String)>
9 astore_1
10 aload_1
11 ldc #1 <String "Lost!!">
13 invokevirtual #15 <Method java.lang.StringBuffer append(java.lang.String)>
16 pop
The bytecode at locations 0 to 9 is executed for the first line of code:
StringBuffer str = new StringBuffer("Stanford ");
The bytecode at location 10 to 16 is then executed for the concatenation:
str.append("Lost!!");
Notice that, as is the case in the first example, this code invokes the append method of a StringBuffer object. Unlike the first example, however, there is no need to create a temporary StringBuffer and then convert it into a String object. This code creates only one object, the StringBuffer, at location 0.
In conclusion, StringBuffer concatenation is significantly faster than String concatenation. Obviously, StringBuffers should be used in this type of operation when possible. If the functionality of the String class is desired, consider using a StringBuffer for concatenation and then performing one conversion to String.

By printing the hashcode of the String/StringBuffer object after any append operation also prove, String object is getting recreated internally every time with new values rather than using the same String object.
public class MutableImmutable {
/**
* #param args
*/
public static void main(String[] args) {
System.out.println("String is immutable");
String s = "test";
System.out.println(s+"::"+s.hashCode());
for (int i = 0; i < 10; i++) {
s += "tre";
System.out.println(s+"::"+s.hashCode());
}
System.out.println("String Buffer is mutable");
StringBuffer strBuf = new StringBuffer("test");
System.out.println(strBuf+"::"+strBuf.hashCode());
for (int i = 0; i < 10; i++) {
strBuf.append("tre");
System.out.println(strBuf+"::"+strBuf.hashCode());
}
}
}
Output:
It prints object value along with its hashcode
String is immutable
test::3556498
testtre::-1422435371
testtretre::-1624680014
testtretretre::-855723339
testtretretretre::2071992018
testtretretretretre::-555654763
testtretretretretretre::-706970638
testtretretretretretretre::1157458037
testtretretretretretretretre::1835043090
testtretretretretretretretretre::1425065813
testtretretretretretretretretretre::-1615970766
String Buffer is mutable
test::28117098
testtre::28117098
testtretre::28117098
testtretretre::28117098
testtretretretre::28117098
testtretretretretre::28117098
testtretretretretretre::28117098
testtretretretretretretre::28117098
testtretretretretretretretre::28117098
testtretretretretretretretretre::28117098
testtretretretretretretretretretre::28117098

A StringBuffer or its younger and faster brother StringBuilder is preferred whenever you're going do to a lot of string concatenations in flavor of
string += newString;
or equivalently
string = string + newString;
because the above constructs implicitly creates new string everytime which will be a huge performance and drop. A StringBuffer / StringBuilder is under the hoods best to be compared with a dynamically expansible List<Character>.

A String is an immutable character array.
A StringBuffer is a mutable character array. Often converted back to String when done mutating.
Since both are an array, the maximum size for both is equal to the maximum size of an integer, which is 2^31-1 (see JavaDoc, also check out the JavaDoc for both String and StringBuffer).This is because the .length argument of an array is a primitive int. (See Arrays).

String is immutable, meaning that when you perform an operation on a String you are really creating a whole new String.
StringBuffer is mutable, and you can append to it as well as reset its length to 0.
In practice, the compiler seems to use StringBuffer during String concatenation for performance reasons.

String is immutable.
Why? Check here.
StringBuffer is not. It is thread safe.
Further questions like when to use which and other concepts can be figured out following this.
Hope this helps.

While I understand that this is not a major differentiating factor, I noticed today that StringBuffer(and StringBuilder) provides some interesting methods that String doesn't.
reverse()
setCharAt()

The differences are
Only in String class + operator is overloaded. We can concat two String object using + operator, but in the case of StringBuffer we can't.
String class is overriding toString(), equals(), hashCode() of Object class, but StringBuffer only overrides toString().
String s1 = new String("abc");
String s2 = new String("abc");
System.out.println(s1.equals(s2)); // output true
StringBuffer sb1 = new StringBuffer("abc");
StringBuffer sb2 = new StringBuffer("abc");
System.out.println(sb1.equals(sb2)); // output false
String class is both Serializable as well as Comparable, but StringBuffer is only Serializable.
Set<StringBuffer> set = new TreeSet<StringBuffer>();
set.add(sb1);
set.add(sb2);
System.out.println(set); // gives ClassCastException because there is no Comparison mechanism
We can create a String object with and without new operator, but StringBuffer object can only be created using new operator.
String is immutable but StringBuffer is mutable.
StringBuffer is synchronized, whereas String ain't.
StringBuffer is having an in-built reverse() method, but String dosen't have it.

Performance wise StringBuffer is much better than String ; because whenever you apply concatenation on String Object then new String object are created on each concatenation.
Principal Rule : String are immutable(Non Modifiable) and StringBuffer are mutable(Modifiable)
Here is the programmatic experiment where you get the performance difference
public class Test {
public static int LOOP_ITERATION= 100000;
public static void stringTest(){
long startTime = System.currentTimeMillis();
String string = "This";
for(int i=0;i<LOOP_ITERATION;i++){
string = string+"Yasir";
}
long endTime = System.currentTimeMillis();
System.out.println(endTime - startTime);
}
public static void stringBufferTest(){
long startTime = System.currentTimeMillis();
StringBuffer stringBuffer = new StringBuffer("This");
for(int i=0;i<LOOP_ITERATION;i++){
stringBuffer.append("Yasir");
}
long endTime = System.currentTimeMillis();
System.out.println(endTime - startTime);
}
public static void main(String []args){
stringTest()
stringBufferTest();
}
}
Output of String are in my machine
14800
Output of StringBuffer are in my machine
14

Related

Delete char at position in string

Currently, I am working on a project that requires to delete a char at a set position in a string. Is there a simple way to do this?
Use a StringBuilder, which has the method deleteCharAt(). Then, you can just use stringBuilder.toString() to get your string.
EDIT, here's an example:
public static void main(String[] args) {
String string = "bla*h";
StringBuilder sb = new StringBuilder(string);
sb.deleteCharAt(3);
// Prints out "blah"
System.out.println(sb.toString());
}
Strings are immutable ! But to accomplish your task, you can
Copy the substring from the start of the string to the character that has to be deleted
Copy the substring from the character that has to be deleted to the end of the String.
Append the second String to the first one.
For example, let's say you have to remove the third character:
String input = "Hello, World";
String first = input.substring(0, 3);
String second = input.substring(4);
String result = first + second;
You can convert your string to StringBuilder, which have convinient deletaCharAt method.
String strWithoutChar = new StringBuilder(yourString).deleteCharAt(yourIndex).toString();
But keep in mind, this gives to you ability to remove some boilerplate code, but it takes more memory in compassion to using String#substring method.
The way you would do this is by copying the oldstring into a newstring, being careful to remove the one character, like so:
String newString = oldString.substring(0, index) + oldString.substring(index+1);
Keep in mind that if you are doing this several times, constantly making new strings is rather inefficient.
Whatever is being said here by fellow scholars, I agree to them that it gives the correct answer. But if you are dealing with a production level program where every loophole gets magnified, I would suggest you to not use "Substring" method of string because:
(1). substring method actually leaves the parent string unflagged for garbage collector. Due to this garbage collector cannot clean it up in its process, the heap space gets occupied and unused parent strings still remains to exist in the heap space even when it is\ not in use.
(2). If you deal with a number of string manipulations such as these, it may eventually result in 'Out of Heap Memory' exception which is not desirable at any point in time in the program.
Use char array and its manipulations to achieve what you want :
public static void fn1()
{
String a = "Stack Overflow";
char[] b = a.toCharArray();
j // index position of the character that you want to delete
for(int i=j;i<b.length-1;i++)
{
b[i]=b[i+1];
}
b[b.length-1]='\000'; // '\000' is the null character
System.out.println(new String(b));
}
An alternative is to use the substring method but using concat instead of +
String removeCharAt(String s, int index) {
return s.substring(0, index).concat(s.substring(index + 1));
}

How do I reclaim memory after parsing via substrings? intern() or new String()?

Short version: If you call string.substring(n,m).intern(), does the string table retain the substring or the original string?
...But I'm not sure that's the right question to ask, so here's the long version:
I'm working with legacy Java code (PCGen) that parses files by slurping each in as one big string and then using String.split, .trim, .substring, and StringTokenizer to decompose them into tokens. This is very efficient for parsing, because none of those methods copy the original string, but all point at parts of a shared char[].
After parsing is over, I want to reclaim some memory. Only a few small substrings of the original big string are needed, but the strong reference keeps the big string from being collected. And later I'm suffering OOM, I believe due in part to that huge heap impact of lots of parsed files.
I know I can trim the big string down via new String(String)(copy-on-write). And I know I can reduce string duplication via String.intern (which is important because there's a lot of redundancy in the parsed files). Do I need to use both to reclaim the greatest quantity of heap, or does .intern() do both? Reading the OpenJDK7 hotspot source code (hotspot/src/share/vm/classfile/symbolTable.cpp) it looks like the string table keeps the whole string and does not trim it for offset/length at all. So I think I need to make a new String and then intern that result. Right?
All that said, switching to a streaming parser would be a big win in terms of memory, but that's too big a change for the short term.
You can use new String(String) and the intern() method and this will take a copy as required for up to Java 7 update 4. From Java 7 update 5 substring will take a deeper copy, but you may still want to use intern(). Note: Java 7 uses the heap, not the perm gen to store String literals.
public static void main(String[] args) {
char[] chars = new char[128];
Arrays.fill(chars, 'A');
String a128 = new String(chars);
printValueFor("a128", a128);
String a16 = a128.substring(0, 16);
printValueFor("a16", a16);
}
public static void printValueFor(String desc, String s) {
try {
Field value = String.class.getDeclaredField("value");
value.setAccessible(true);
char[] valueArr = (char[]) value.get(s);
System.out.println(desc + ": " + Integer.toHexString(System.identityHashCode(valueArr)) + ", len=" + valueArr.length);
} catch (Exception e) {
throw new AssertionError(e);
}
}
on Java 7 update 4 prints
a128: 513e86ec, len=128
a16: 53281264, len=16
I would expect that Java 6 does not do this.
We can test it. String holds its character array in a field
private final char value[];
let's see what happens after substring(); intern();
Field f = String.class.getDeclaredField("value");
f.setAccessible(true);
String s1 = "12345";
String s2 = s1.substring(1, 2);
String s3 = s2.intern();
System.out.println(f.get(s2) == f.get(s1));
System.out.println(f.get(s3) == f.get(s2));
output
true
true
that is, all 3 strings share the same character array

Is this creating 12 string objects?

I'm trying to understand if this code below creates 12 objects for a string like "stephan"
public String reverse(String str) {
if ((null == str) || (str.length() <= 1)) {
return str;
}
return reverse(str.substring(1)) + str.charAt(0);
}
This recursively reverses a string. I understand how it works. But I was thinking if there is a relationship in this case between the length of the strings and number of string objects created through concatenation?
Yes, it will create tons of string objects.
Every recursive call to "reverse()" will create 2:
str.substring(1) will create a new String object
reverse() call will create a new string for its return value, but we will NOT count that since that's counted when analyzing that recursive call (e.g. it will be the string from bullet point #3 from the next reverse() call).
And since Java Strings are immutable, adding a char via "+" will create a second String object.
Therefore, for a string of length N, it will create (N-1)*2 objects (since a reverse of 1-char string does NOT create new strings); so for "stephan"'s 7 characters, it will create 6*2=12 string objects.
Theorem:
When a string is N characters long, #Phoenix's reverse implementation will create (N-1)*3 new objects.
Proof (by induction):
When str is 1 character long, it is returned directly. (1*1)*3 = 0.
When str is N characters long:
a new String will be created by .substring(1).
by the induction hypothesis, the call to reverse(...) will be returned after (N-2)*3 objects have been created.
a new StringBuilder will be created to append the string and first char (you can see this by de-compiling your byte-code).
a new String will be created by StringBuilder.toString()--this is the return value.
Altogether, there were 3 + (N-2)*3 = (N-2 + 1)*3 = (N-1)*3 objects created.
QED.
[Edit] StringBuilders:
StringBuilder (extending AbstractStringBuilder) does its own fancy footwork:
When an StringBuilder is constructed, it is initialized with a char[] of size 16.
When you append something more than it's present size, it throws that away and creates a new char[] of size (<old size> + <size of new data> + 1) * 2.
So, as soon as your input string is > 16 characters, you have essentially 2x as much StringBuilder capacity as you need. (When the input string size is less, you've got more char[] than you need.)
Considering Strings are essentially char[]s (with a few ints for good measure), you're effectively using 4 times the length of the substring in char[]s -- at each step. :(

Using String or StringBuffer in Java: which is better?

I read a lot about using StringBuffer and String especially where concatenation is concerned in Java and whether one is thread safe or not.
So, in various Java methods, which should be used?
For example, in a PreparedStatement, should query be a StringBuffer:
String query = ("SELECT * " +
"FROM User " +
"WHERE userName = ?;");
try {
ps = connection.prepareStatement(query);
And then again, in a String utility methods like:
public static String prefixApostrophesWithBackslash(String stringIn) {
String stringOut = stringIn.replaceAll("'", "\\\\'");
return stringOut;
}
And:
// Removes a char from a String.
public static String removeChar(String stringIn, char c) {
String stringOut = ("");
for (int i = 0; i < stringIn.length(); i++) {
if (stringIn.charAt(i) != c) {
stringOut += stringIn.charAt(i);
}
}
return stringOut;
}
Should I be using StringBuffers? Especially where repalceAll is not available for such objects anyway.
Thanks
Mr Morgan.
Thanks for all the advice. StringBuffers have been replaced with StringBuilders and Strings replaced with StringBuilders where I've thought it best.
You almost never need to use StringBuffer.
Instead of StringBuffer you probably mean StringBuilder. A StringBuffer is like a StringBuilder except that it also offers thread safety. This thread safety is rarely needed in practice and will just cause your code to run more slowly.
Your question doesn't seem to be about String vs StringBuffer, but about using built-in methods or implementing the code yourself. If there is a built-in method that does exactly what you want, you should probably use it. The chances are it is much better optimized than the code you would write.
There is no simple answer (apart from repeating the mantra of StringBuilder versus StringBuffer ... ). You really have understand a fair bit about what goes on "under the hood" in order to pick the most efficient solution.
In your first example, String is the way to go. The Java compiler can generate pretty much optimal code (using a StringBuilder if necessary) for any expression consisting of a sequence of String concatenations. And, if the strings that are concatenated are all constants or literals, the compiler can actually do the concatenation at compile time.
In your second example, it is not entirely clear whether String or StringBuilder would be better ... or whether they would be roughly equivalent. One would need to look at the code of the java.util.regex.Matcher class to figure this out.
EDIT - I looked at the code, and actually it makes little difference whether you use a String or StringBuilder as the source. Internally the Matcher.replaceAll method creates a new StringBuilder and fills it by appending chunks from the source String and the replacement String.
In your third example, a StringBuilder would clearly be best. A current generation Java compiler is not able to optimize the code (as written) to avoid creating a new String as each character is added.
For the below segment of code
// Removes a char from a String.
public static String removeChar(String stringIn, char c) {
String stringOut = ("");
for (int i = 0; i < stringIn.length(); i++) {
if (stringIn.charAt(i) != c) {
stringOut += stringIn.charAt(i);
}
}
return stringOut;
}
You could just do stringIn.replaceAll(c+"","")
Even in MT code, it's unusual to have multiple threads append stuff to a string. StringBuilder is almost always preferred to StringBuffer.
Modern compilers optimize the code already. So some String additions will be optimized to use StringBuilder and we can keep the String additions if we think, it increases readibility.
Example 1:
String query = ("SELECT * " +
"FROM User " +
"WHERE userName = ?;");
will be optimized to somthing like:
StringBuiler sb = new StringBuilder();
sb.append("SELECT * ");
sb.append("FROM User ");
sb.append("WHERE userName = ?;");
String query = sb.toString();
Example 2:
String numbers = "";
for (int i = 0;i < 20; i++)
numbers = numbers + i;
This can't be optimized and we should use a StringBuilder in code.
I made this observation for SUN jdk1.5+. So for older Java versions or different jdks it can be different. There it could be save to always code StringBuilder (or StringBuffer for jdk 1.4.2 and older).
For cases which can be considered single threaded, the best would be StringBuilder. It does not add any synchronization overhead, while StringBuffer does.
String concatenation by '+' operator is "good" only when you're lazy to use StringBuilder or just want to keep the code easily readable and it is acceptable from performance point of view, like in startup log message "LOG.info("Starting instance " + inst_id + " of " + app_name);"

What is the difference between String and StringBuffer in Java?

What is the difference between String and StringBuffer in Java?
Is there a maximum size for String?
String is used to manipulate character strings that cannot be changed (read-only and immutable).
StringBuffer is used to represent characters that can be modified.
Performance wise, StringBuffer is faster when performing concatenations. This is because when you concatenate a String, you are creating a new object (internally) every time since String is immutable.
You can also use StringBuilder which is similar to StringBuffer except it is not synchronized. The maximum size for either of these is Integer.MAX_VALUE (231 - 1 = 2,147,483,647) or maximum heap size divided by 2 (see How many characters can a Java String have?).
More information here.
A String is immutable, i.e. when it's created, it can never change.
A StringBuffer (or its non-synchronized cousin StringBuilder) is used when you need to construct a string piece by piece without the performance overhead of constructing lots of little Strings along the way.
The maximum length for both is Integer.MAX_VALUE, because they are stored internally as arrays, and Java arrays only have an int for their length pseudo-field.
The performance improvement between Strings and StringBuffers for multiple concatenation is quite significant. If you run the following test code, you will see the difference. On my ancient laptop with Java 6, I get these results:
Concat with String took: 1781ms
Concat with StringBuffer took: 0ms
public class Concat
{
public static String concatWithString()
{
String t = "Cat";
for (int i=0; i<10000; i++)
{
t = t + "Dog";
}
return t;
}
public static String concatWithStringBuffer()
{
StringBuffer sb = new StringBuffer("Cat");
for (int i=0; i<10000; i++)
{
sb.append("Dog");
}
return sb.toString();
}
public static void main(String[] args)
{
long start = System.currentTimeMillis();
concatWithString();
System.out.println("Concat with String took: " + (System.currentTimeMillis() - start) + "ms");
start = System.currentTimeMillis();
concatWithStringBuffer();
System.out.println("Concat with StringBuffer took: " + (System.currentTimeMillis() - start) + "ms");
}
}
String StringBuffer
Immutable Mutable
String s=new String("karthik"); StringBuffer sb=new StringBuffer("karthik")
s.concat("reddy"); sb.append("reddy");
System.out.println(s); System.out.println(sb);
O/P:karthik O/P:karthikreddy
--->once we created a String object ---->once we created a StringBuffer object
we can't perform any changes in the existing we can perform any changes in the existing
object.If we are trying to perform any object.It is nothing but mutablity of
changes with those changes a new object of a StrongBuffer object
will be created.It is nothing but Immutability
of a String object
Use String--->If you require immutabilty
Use StringBuffer---->If you require mutable + threadsafety
Use StringBuilder--->If you require mutable + with out threadsafety
String s=new String("karthik");
--->here 2 objects will be created one is heap and the other is in stringconstantpool(scp) and s is always pointing to heap object
String s="karthik";
--->In this case only one object will be created in scp and s is always pointing to that object only
String is an immutable class. This means that once you instantiate an instance of a string like so:
String str1 = "hello";
The object in memory cannot be altered. Instead you will have to create a new instance, copy the old String and append whatever else as in this example:
String str1 = "hello";
str1 = str1 + " world!";
What is really happening hear is that we are NOT updating the existing str1 object... we are reallocating new memory all together, copying the "hello" data and appending " world!" to the end, then settings the str1 reference to point to this new memory. So it really looks more like this under the hood:
String str1 = "hello";
String str2 = str1 + " world!";
str1 = str2;
So it follows that this "copy + paste and move stuff around in memory" process can be very expensive if done repitively especially recursively.
When you are in that situation of having to do things over and over utilize StringBuilder. It is mutable and can append strings to the end of the current one because it's back by an [growing array] (not 100% if that is the actual data structure, could be a list).
From the API:
A thread-safe, mutable sequence of characters. A string buffer is like a String, but can be modified. At any point in time it contains some particular sequence of characters, but the length and content of the sequence can be changed through certain method calls.
A StringBuffer is used to create a single string from many strings, e.g. when you want to append parts of a String in a loop.
You should use a StringBuilder instead of a StringBuffer when you have only a single Thread accessing the StringBuffer, since the StringBuilder is not synchronized and thus faster.
AFAIK there is no upper limit for String size in Java as a language, but the JVMs probably have an upper limit.
I found interest answer for compare performance String vs StringBuffer by Reggie Hutcherso
Source: http://www.javaworld.com/javaworld/jw-03-2000/jw-0324-javaperf.html
Java provides the StringBuffer and String classes, and the String class is used to manipulate character strings that cannot be changed. Simply stated, objects of type String are read only and immutable. The StringBuffer class is used to represent characters that can be modified.
The significant performance difference between these two classes is that StringBuffer is faster than String when performing simple concatenations. In String manipulation code, character strings are routinely concatenated. Using the String class, concatenations are typically performed as follows:
String str = new String ("Stanford ");
str += "Lost!!";
If you were to use StringBuffer to perform the same concatenation, you would need code that looks like this:
StringBuffer str = new StringBuffer ("Stanford ");
str.append("Lost!!");
Developers usually assume that the first example above is more efficient because they think that the second example, which uses the append method for concatenation, is more costly than the first example, which uses the + operator to concatenate two String objects.
The + operator appears innocent, but the code generated produces some surprises. Using a StringBuffer for concatenation can in fact produce code that is significantly faster than using a String. To discover why this is the case, we must examine the generated bytecode from our two examples. The bytecode for the example using String looks like this:
0 new #7 <Class java.lang.String>
3 dup
4 ldc #2 <String "Stanford ">
6 invokespecial #12 <Method java.lang.String(java.lang.String)>
9 astore_1
10 new #8 <Class java.lang.StringBuffer>
13 dup
14 aload_1
15 invokestatic #23 <Method java.lang.String valueOf(java.lang.Object)>
18 invokespecial #13 <Method java.lang.StringBuffer(java.lang.String)>
21 ldc #1 <String "Lost!!">
23 invokevirtual #15 <Method java.lang.StringBuffer append(java.lang.String)>
26 invokevirtual #22 <Method java.lang.String toString()>
29 astore_1
The bytecode at locations 0 through 9 is executed for the first line of code, namely:
String str = new String("Stanford ");
Then, the bytecode at location 10 through 29 is executed for the concatenation:
str += "Lost!!";
Things get interesting here. The bytecode generated for the concatenation creates a StringBuffer object, then invokes its append method: the temporary StringBuffer object is created at location 10, and its append method is called at location 23. Because the String class is immutable, a StringBuffer must be used for concatenation.
After the concatenation is performed on the StringBuffer object, it must be converted back into a String. This is done with the call to the toString method at location 26. This method creates a new String object from the temporary StringBuffer object. The creation of this temporary StringBuffer object and its subsequent conversion back into a String object are very expensive.
In summary, the two lines of code above result in the creation of three objects:
A String object at location 0
A StringBuffer object at location 10
A String object at location 26
Now, let's look at the bytecode generated for the example using StringBuffer:
0 new #8 <Class java.lang.StringBuffer>
3 dup
4 ldc #2 <String "Stanford ">
6 invokespecial #13 <Method java.lang.StringBuffer(java.lang.String)>
9 astore_1
10 aload_1
11 ldc #1 <String "Lost!!">
13 invokevirtual #15 <Method java.lang.StringBuffer append(java.lang.String)>
16 pop
The bytecode at locations 0 to 9 is executed for the first line of code:
StringBuffer str = new StringBuffer("Stanford ");
The bytecode at location 10 to 16 is then executed for the concatenation:
str.append("Lost!!");
Notice that, as is the case in the first example, this code invokes the append method of a StringBuffer object. Unlike the first example, however, there is no need to create a temporary StringBuffer and then convert it into a String object. This code creates only one object, the StringBuffer, at location 0.
In conclusion, StringBuffer concatenation is significantly faster than String concatenation. Obviously, StringBuffers should be used in this type of operation when possible. If the functionality of the String class is desired, consider using a StringBuffer for concatenation and then performing one conversion to String.
By printing the hashcode of the String/StringBuffer object after any append operation also prove, String object is getting recreated internally every time with new values rather than using the same String object.
public class MutableImmutable {
/**
* #param args
*/
public static void main(String[] args) {
System.out.println("String is immutable");
String s = "test";
System.out.println(s+"::"+s.hashCode());
for (int i = 0; i < 10; i++) {
s += "tre";
System.out.println(s+"::"+s.hashCode());
}
System.out.println("String Buffer is mutable");
StringBuffer strBuf = new StringBuffer("test");
System.out.println(strBuf+"::"+strBuf.hashCode());
for (int i = 0; i < 10; i++) {
strBuf.append("tre");
System.out.println(strBuf+"::"+strBuf.hashCode());
}
}
}
Output:
It prints object value along with its hashcode
String is immutable
test::3556498
testtre::-1422435371
testtretre::-1624680014
testtretretre::-855723339
testtretretretre::2071992018
testtretretretretre::-555654763
testtretretretretretre::-706970638
testtretretretretretretre::1157458037
testtretretretretretretretre::1835043090
testtretretretretretretretretre::1425065813
testtretretretretretretretretretre::-1615970766
String Buffer is mutable
test::28117098
testtre::28117098
testtretre::28117098
testtretretre::28117098
testtretretretre::28117098
testtretretretretre::28117098
testtretretretretretre::28117098
testtretretretretretretre::28117098
testtretretretretretretretre::28117098
testtretretretretretretretretre::28117098
testtretretretretretretretretretre::28117098
A StringBuffer or its younger and faster brother StringBuilder is preferred whenever you're going do to a lot of string concatenations in flavor of
string += newString;
or equivalently
string = string + newString;
because the above constructs implicitly creates new string everytime which will be a huge performance and drop. A StringBuffer / StringBuilder is under the hoods best to be compared with a dynamically expansible List<Character>.
A String is an immutable character array.
A StringBuffer is a mutable character array. Often converted back to String when done mutating.
Since both are an array, the maximum size for both is equal to the maximum size of an integer, which is 2^31-1 (see JavaDoc, also check out the JavaDoc for both String and StringBuffer).This is because the .length argument of an array is a primitive int. (See Arrays).
String is immutable, meaning that when you perform an operation on a String you are really creating a whole new String.
StringBuffer is mutable, and you can append to it as well as reset its length to 0.
In practice, the compiler seems to use StringBuffer during String concatenation for performance reasons.
String is immutable.
Why? Check here.
StringBuffer is not. It is thread safe.
Further questions like when to use which and other concepts can be figured out following this.
Hope this helps.
While I understand that this is not a major differentiating factor, I noticed today that StringBuffer(and StringBuilder) provides some interesting methods that String doesn't.
reverse()
setCharAt()
The differences are
Only in String class + operator is overloaded. We can concat two String object using + operator, but in the case of StringBuffer we can't.
String class is overriding toString(), equals(), hashCode() of Object class, but StringBuffer only overrides toString().
String s1 = new String("abc");
String s2 = new String("abc");
System.out.println(s1.equals(s2)); // output true
StringBuffer sb1 = new StringBuffer("abc");
StringBuffer sb2 = new StringBuffer("abc");
System.out.println(sb1.equals(sb2)); // output false
String class is both Serializable as well as Comparable, but StringBuffer is only Serializable.
Set<StringBuffer> set = new TreeSet<StringBuffer>();
set.add(sb1);
set.add(sb2);
System.out.println(set); // gives ClassCastException because there is no Comparison mechanism
We can create a String object with and without new operator, but StringBuffer object can only be created using new operator.
String is immutable but StringBuffer is mutable.
StringBuffer is synchronized, whereas String ain't.
StringBuffer is having an in-built reverse() method, but String dosen't have it.
Performance wise StringBuffer is much better than String ; because whenever you apply concatenation on String Object then new String object are created on each concatenation.
Principal Rule : String are immutable(Non Modifiable) and StringBuffer are mutable(Modifiable)
Here is the programmatic experiment where you get the performance difference
public class Test {
public static int LOOP_ITERATION= 100000;
public static void stringTest(){
long startTime = System.currentTimeMillis();
String string = "This";
for(int i=0;i<LOOP_ITERATION;i++){
string = string+"Yasir";
}
long endTime = System.currentTimeMillis();
System.out.println(endTime - startTime);
}
public static void stringBufferTest(){
long startTime = System.currentTimeMillis();
StringBuffer stringBuffer = new StringBuffer("This");
for(int i=0;i<LOOP_ITERATION;i++){
stringBuffer.append("Yasir");
}
long endTime = System.currentTimeMillis();
System.out.println(endTime - startTime);
}
public static void main(String []args){
stringTest()
stringBufferTest();
}
}
Output of String are in my machine
14800
Output of StringBuffer are in my machine
14

Categories

Resources