< Prev
Next >



StringBuffer Class





With String class, we can make unmodifiable strings, i.e. immutable but by using StringBuffer class we can not only create strings of characters but can also modify them, which makes them mutable. StringBuffer class is also a thread-safe class as its methods are marked synchronized.




When StringBuffer class is used?







Constructors of StringBuffer class


public StringBuffer()
Creates a StringBuffer object with initial capacity of 16 characters.

public StringBuffer(String str)
Creates a StringBuffer object using a String str.

public StringBuffer(int capacity)
Creates a StringBuffer object with a defined capacity of characters.




Creating an empty StringBuffer object


// StringBuffer Class Example

class StringBufferEx
{
public static void main(String... ar)
{
StringBuffer sb= new StringBuffer(); //Creating an empty StringBuffer object.
System.out.println("Original StringBuffer value : "+ sb);
sb.append("Stay");
sb.append("Positive");
System.out.println("Modified StringBuffer value : "+ sb);
}
}


Output is :


Original StringBuffer value is : 
Modified StringBuffer value is : StayPositive


Program Analysis







Creating and initializing a StringBuffer object using a String


// StringBuffer Class Example

class StringBufferEx
{
public static void main(String... ar)
{
StringBuffer sb= new StringBuffer("Keep");

System.out.println("Original StringBuffer value : "+ sb);
sb.append("Smiling");
System.out.println("Modified StringBuffer value : "+ sb);
}
}


Output is :


Original StringBuffer value : Keep
Modified StringBuffer value : KeepSmiling


Program Analysis







Finding the index of a substring in a string created by StringBuilder


class A
{
public static void main(String... ar()
{
StringBuffer sb= new StringBuffer("Blue"); 
System.out.println("Original StringBuffer value : "+ sb); 
int index = sb.indexOf("ue"); //Finding the index of substring "ue" in StringBuffer string.
System.out.println("index of ue  in StringBuffer string  : "+  index);
}


Output is :


Original StringBuffer string value : Blue
index of ue in StringBuffer string : 2




Please share this article -

Facebook Google Pinterest Reddit Tumblr Twitter



< Prev
Next >
< substring() method
StringBuffer methods >
Please subscribe our social media channels for notifications, we post a new article everyday.

Decodejava Google+ Page Decodejava Facebook Page  DecodeJava Twitter Page

Coming Next
-
Python

Ad2