java.lang.StringBuffer Class

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

In this tutorial you can learn how to create StringBuffer and how to use StringBuffer.

java.lang.StringBuffer Class Example
/* StringBuffer Example with Default Constructor */
/* Save with file name StringBufferExample1.java */

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

public class StringBufferExample2
{
	public static void main(String args[])
	{
		//DECLARATION
		StringBuffer s1;
		//CREATE INSTANCE USING PARAMETER CONSTRUCTOR
		s1 = new StringBuffer("Huda Tutorials");
		//OUTPUT
		System.out.println("StringBuffer value : " + s1);
	}
}
                        

In the following example you can learn how to reverse string in java. 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.

java.lang.StringBuffer Class Example 3
/* Save with file name StringBufferExample3.java */

public class StringBufferExample3
{
	public static void main(String args[])
	{
		//DECLARATION
		StringBuffer s1;
		//CREATE INSTANCE USING PARAMETER CONSTRUCTOR
		s1 = new StringBuffer("abcd");
		//REVERSE STRING USING REVERSE METHOD
		System.out.println("Reverse String is : " + s1.reverse());
	}
}
                        

In the following example you can learn how to append String into StringBuffer.

java.lang.StringBuffer Class Example 4
/* Save with file name StringBufferExample4.java */

public class StringBufferExample4
{
	public static void main(String args[])
	{
		//DECLARATION
		StringBuffer s1;
		//CREATE INSTANCE USING PARAMETER CONSTRUCTOR
		s1 = new StringBuffer("Huda");
		s1.append("Tutorials");
		//APPENDED STRING
		System.out.println("String is : " + s1.toString());
	}
}