HudaTutorials.com

java lang StringBuffer Class - StringBuffer in Java

Last updated on

java.lang.StringBuffer Class

StringBuffer Class in Java

The Java StringBuffer class represents character strings like Java String class, but Java StringBuffer class can be modified. The length and content of the sequence can be changed through certain method calls. Java StringBuffer objects are mutable their values can be changed after they are created. StringBuffer is safe for use by multiple threads.

Whenever an operation occurs involving a source sequence (such as appending or inserting from a source sequence), this class synchronizes only on the string buffer performing the operation, not on the source. Note that while StringBuffer is designed to be safe to use concurrently from multiple threads, if the constructor or the append or insert operation is passed a source sequence that is shared across threads, the calling code must ensure that the operation has a consistent and unchanging view of the source sequence for the duration of the operation. This could be satisfied by the caller holding a lock during the operation's call, by using an immutable source sequence, or by not sharing the source sequence across threads.

Every string buffer has a capacity. As long as the length of the character sequence contained in the string buffer does not exceed the capacity, it is not necessary to allocate a new internal buffer array. If the internal buffer overflows, it is automatically made larger.

Unless otherwise noted, passing a null argument to a constructor or method in this class will cause a NullPointerException to be thrown.

As of release JDK 5, this class has been supplemented with an equivalent class designed for use by a single thread, StringBuilder. The StringBuilder class should generally be used in preference to this one, as it supports all of the same operations but it is faster, as it performs no synchronization.

Note :

StringBuffer implements Comparable but does not override equals. Thus, the natural ordering of StringBuffer is inconsistent with equals. Care should be exercised if StringBuffer objects are used as keys in a SortedMap or elements in a SortedSet. See Comparable, SortedMap, or SortedSet for more information.

What is StringBuffer in Java ?

StringBuffer is a peer class of String that provides much of the functionality of strings. String represents fixed-length, immutable character sequences while StringBuffer represents growable and writable character sequences. Java StringBuffer may have characters and substrings inserted in the middle or appended to the end. StringBuffer in Java is safe for use by multiple threads.

Why StringBuffer is faster than String ?

String class objects are immutable whereas StringBuffer objects are mutable. StringBuffer class is synchronized. 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.

Why is StringBuffer synchronized ?

The object created through StringBuffer is stored in the heap. StringBuffer has the same methods as the StringBuilder , but each method in StringBuffer is synchronized that is StringBuffer is thread safe . Due to this it does not allow two threads to simultaneously access the same method .

Is StringBuffer thread safe ?

StringBuffer has the same methods as the StringBuilder , but each method in StringBuffer is synchronized that is StringBuffer is thread safe . because of this it does not allow two threads to simultaneously access the same method . Each method can be accessed by one thread at a time .

How to convert Java StringBuffer to String ?

The toString() method of Java StringBuffer class can be used to convert StringBuffer content to a String. This method returns a String object that represents the contents of StringBuffer.

What is the Difference Between String and StringBuffer ?

String object is slower in performance whereas, the StringBuffer object is faster. String object consumes more memory whereas, StringBuffer objects consumes less memory. String objects are stored in a constant pool whereas, StringBuffer objects are stored on heap memory.

How to clear or delete the content of StringBuffer ?

The StringBuffer is always been using for the String concatenation. However Java StringBuffer class does not provide a method to clear the existing contents of StringBuffer . If you want to clear or delete the contents of StringBuffer you should use the delete(int start, int end) method of StringBuffer .

What are the principal operations on a StringBuffer in Java ?

The principal operations on a StringBuffer are the append and insert methods, which are overloaded so as to accept data of any type. Each effectively converts a given datum to a string and then appends or inserts the characters of that string to the string buffer. The append method always adds these characters at the end of the buffer; the insert method adds the characters at a specified point.

For example, if z refers to a string buffer object whose current contents are "start", then the method call z.append("le") would cause the string buffer to contain "startle", whereas z.insert(4, "le") would alter the string buffer to contain "starlet".

In general, if sb refers to an instance of a StringBuffer, then sb.append(x) has the same effect as sb.insert(sb.length(), x).

Following Java StringBuffer class example you can learn how to create Java StringBuffer and how to use Java StringBuffer.

Java StringBuffer class Example with Default Constructor

/*  Java StringBuffer class Example with Default Constructor
    Save with file name StringBufferExample1.java   */
public class StringBufferExample1
{
	public static void main(String args[])
	{
		// Java StringBuffer DECLARATION
		StringBuffer s1;
		// CREATE Java StringBuffer INSTANCE USING DEFAULT CONSTRUCTOR
		// THE VALUE OF Java StringBuffer IS EMPTY
		s1 = new StringBuffer();
		// Java StringBuffer OUTPUT EMPTYSTRING
		System.out.println("Java StringBuffer value : " + s1);
	}
}

Java StringBuffer Example with Parameter Constructor

/*  Java StringBuffer Example with Parameter Constructor
    Save with file name StringBufferExample2.java   */
public class StringBufferExample2
{
	public static void main(String args[])
	{
		// Java StringBuffer DECLARATION
		StringBuffer s1;
		// CREATE Java StringBuffer INSTANCE USING PARAMETER CONSTRUCTOR
		s1 = new StringBuffer("Huda Tutorials");
		// Java StringBuffer OUTPUT
		System.out.println("StringBuffer value : " + s1);
	}
}

How to Reverse String in java using StringBuffer ?

By using the Java StringBuffer class you can reverse the string in java. In the following Java StringBuffer example you can learn how to reverse string in java using StringBuffer.

Most of the interviewer ask a question How to reverse String in java ?. Most of the people fail in this question. Because those are worked on String class not worked on StringBuffer class.

How to reverse string using Java StringBuffer Class

/*  Java StringBuffer Example with how to reverse string in java
    Save with file name StringBufferExample3.java   */
public class StringBufferExample3
{
	public static void main(String args[])
	{
		// Java StringBuffer DECLARATION
		StringBuffer s1;
		// CREATE Java StringBuffer INSTANCE USING PARAMETER CONSTRUCTOR
		s1 = new StringBuffer("abcd");
		// REVERSE STRING USING Java StringBuffer REVERSE METHOD
		System.out.println("Reverse String is : " + s1.reverse());
	}
}

How to append String into Java StringBuffer ?

Following Java StringBuffer class example you can learn how to append String into Java StringBuffer.

How to append String into Java StringBuffer

/*  Java StringBuffer Example with how to append
    String into Java StringBuffer
    Save with file name StringBufferExample4.java   */
public class StringBufferExample4
{
	public static void main(String args[])
	{
		// Java StringBuffer DECLARATION
		StringBuffer s1;
		// CREATE INSTANCE USING PARAMETER CONSTRUCTOR
		s1 = new StringBuffer("Huda");
		s1.append("Tutorials");
		// APPENDED STRING
		System.out.println("String is : " + s1.toString());
	}
}