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?

+60
java string stringbuilder stringbuffer
Mar 13 '10 at 17:25
source share
15 answers

String used to control character strings that cannot be changed (read-only and immutable).

StringBuffer used to represent characters that can be changed.

Performance, StringBuffer faster when performing concatenations. This is because when you concatenate String , you create a new object each time (internally), since String is immutable.

You can also use StringBuilder , which is similar to StringBuffer , except that it is not synchronized. The maximum size for any of them is Integer.MAX_VALUE (2 31 - 1 = 2,147,483,647) or the maximum heap size divided by 2 (see How many characters can a Java String have? ). More details here .

+69
Mar 13 '10 at 17:28
source share

A String immutable, i.e. when it is created, it can never change.

A StringBuffer (or its unsynchronized cousin StringBuilder ) is used when you need to build a string in parts without performance overhead when building a large number of small String along this path.

The maximum length for both is Integer.MAX_VALUE, because they are stored internally as arrays, and Java arrays have only int for their pseudo-field of length.

The performance improvement between String and StringBuffer for multiple concatenation is quite significant. If you run the following test code, you will see the difference. On my old laptop with Java 6, I get the following 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"); } } 
+33
Mar 13 '10 at 17:28
source share
 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 
+22
Mar 22 '13 at 6:54
source share

A string is an immutable class. This means that as soon as you instantiate the string like this:

 String str1 = "hello"; 

An object in memory cannot be modified. Instead, you will need to create a new instance, copy the old line and add everything in this example:

 String str1 = "hello"; str1 = str1 + " world!"; 

In fact, we hear that we are not updating the existing str1 object ... we are reallocating new memory, copying “hello” data and adding “world!”. to the end, then sets the str1 link to point to this new memory. So it really looks more under the hood:

 String str1 = "hello"; String str2 = str1 + " world!"; str1 = str2; 

So, this means that this “copy and paste and move through memory" process can be very expensive if done reticulously especially recursively.

When you are in a situation where you have to do a lot of things, use StringBuilder. It is modified and can add rows to the end of the current one because it is returned [by a growing array] (and not 100%, if this is the actual data structure, it could be a list).

+10
Mar 04 2018-11-11T00:
source share

From the API:

Streaming, variable sequence of characters. The string buffer is similar to String, but can be changed. At any given time, it contains a specific sequence of characters, but the length and contents of the sequence can be changed using certain method calls.

+4
Mar 04 '11 at 16:50
source share

StringBuffer is used to create a single string from many strings, for example. when you want to add parts of a line in a loop.

You should use StringBuilder instead of StringBuffer if you have only one thread accessing StringBuffer, since StringBuilder is out of sync and therefore faster.

AFAIK there is no upper limit for string size in Java as a language, but the JVM probably has an upper limit.

+2
Mar 13 '10 at 17:27
source share

I found an interesting answer to compare String vs StringBuffer performance from 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 control character strings that cannot be changed. Simply put, objects of type String are read only and immutable. The StringBuffer class is used to represent characters that can be changed.

The significant performance difference between the two classes is that StringBuffer is faster than String when doing simple concatenations. In String manipulation code, character strings are usually concatenated. Using the String class, concatenations are usually performed as follows:

  String str = new String ("Stanford "); str += "Lost!!"; 

If you want to use a StringBuffer to perform the same concatenation, you will 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 believe that the second example, which uses the append method to concatenate, is more expensive than the first example, which uses the + operator to concatenate two String objects.

The + operator seems innocent, but the generated code causes some surprises. Using StringBuffer to concatenate can actually produce code that is significantly faster than using String. To find out why this is so, we need to examine the generated bytecode from our two examples. The byte code for an example using String is as follows:

 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 in places 0 through 9 is executed for the first line of code, namely:

  String str = new String("Stanford "); 

Then the bytecode in places 10 through 29 is executed to concatenate:

  str += "Lost!!"; 

It is interesting here. The bytecode generated for concatenation creates a StringBuffer object, then calls its append method: a temporary StringBuffer object is created at location 10, and its append method is called at location 23. Since the String class is immutable, StringBuffer should be used for concatenation.

After concatenation is performed on the StringBuffer object, it must be converted back to String. This is done by calling the toString method at location 26. This method creates a new String object from a temporary StringBuffer object. Creating this temporary StringBuffer object and then converting it back to a String object is very expensive.

Thus, the two lines of code above lead to the creation of three objects:

  • String object at location 0
  • StringBuffer at location 10
  • 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 in places 0 through 9 is executed for the first line of code:

  StringBuffer str = new StringBuffer("Stanford "); 

Then, to concatenate, the bytecode at position 10-16 is executed:

  str.append("Lost!!"); 

Note that, as in the first example, this code calls the method to add a StringBuffer object. However, unlike the first example, there is no need to create a temporary StringBuffer and then convert it to a String object. This code creates only one object, StringBuffer, at location 0.

In conclusion, StringBuffer concatenation is significantly faster than string concatenation. Obviously, StringBuffers should be used in this type of operation whenever possible. If String functionality is required, consider using a StringBuffer to concatenate, and then do one conversion to String.

+2
Nov 23 '10 at 6:55
source share

A String is an immutable array of characters.

A StringBuffer is a mutable array of characters. Often converted back to String when it mutates.

Since both are arrays, the maximum size for both is equal to the maximum integer size, which is 2 ^ 31-1 (see JavaDoc , also check the JavaDoc for both String and StringBuffer ). This is because the .length argument of the array is a primitive int . (See Arrays .)

+1
Mar 13 '10 at 17:29
source share

A StringBuffer or its younger and faster brother StringBuilder preferable whenever you are going to do a lot of string concatenations in flavor

 string += newString; 

or equivalent

 string = string + newString; 

because the above constructions implicitly create a new string every time, which will be a huge performance and decrease. A StringBuffer / StringBuilder is under the hoods that are best compared to a dynamically expandable List<Character> .

+1
Mar 13 '10 at 17:29
source share

A string is immutable, which means that when you perform an operation on a String, you really create a whole new string.

StringBuffer is changed, and you can add to it, as well as reset its length to 0.

In practice, the compiler uses a StringBuffer during string concatenation for performance reasons .

+1
Mar 04 '11 at 16:50
source share
 String is immutable. 

Why? Check here .

 StringBuffer is not. It is thread safe. 

Other questions, for example, when to use, which and other concepts can be understood by following this .

Hope this helps.

+1
Jul 25 '13 at 6:44
source share

Although I understand that this is not the main differentiating factor, today I noticed that StringBuffer (and StringBuilder) provides some interesting methods that String does not support.

  • back()
  • setCharAt ()
+1
Nov 20 '14 at 3:14
source share

Having printed the hash code of the String / StringBuffer object after any addition operation, also prove that the String object is recreated each time with new values, and not 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()); } } } 

Conclusion: It prints the value of an object along with its hash code

  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 
+1
Jun 23 '16 at 6:02
source share

Differences

  • Only in the String class + operator is overloaded. We can concatenate two String objects using the + operator, but in the case of StringBuffer we cannot. Class
  • String overrides toString (), equals (), hashCode () of the 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 
  • Class String - Serializable as well as Comparable , but StringBuffer 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 a new operator, but a StringBuffer can only be created using the new operator.

  • The string is immutable, but the StringBuffer is modified.
  • StringBuffer is synchronized, but String is not.
  • StringBuffer has a built-in reverse () method, but String does not have it.
+1
Jan 17 '17 at 13:28
source share

Effective wise StringBuffer is much better than String; because whenever you apply concatenation to a String Object, a new String object is created on each concatenation.

Rule of thumb: Non Modifiable string and StringBuffer are mutable (modifiable)

Here is a software experiment in which you get a 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(); } } 

Line output in my car 14800

The output of StringBuffer is on my machine 14

0
Jun 11 '16 at 10:21
source share



All Articles