Important methods of StringBuffer

1. append() method: This StringBuffer Java method is used to append the given text in a string. StringBuffer class has various forms of this method we will discuss it later.

class ExampleOfStringBuffer
{  
	public static void main(String args[])
	{  
                // creating a StringBuffer with specified string
                StringBuffer name = new StringBuffer("Ravi"); 
		name.append("kant"); // Appending string in string buffer
		System.out.println("Name of Student = "+ name); 		
	}
}  

Output: Name of Student = Ravikant

2. insert() method: This StringBuffer java method is used to insert the given text in the string at a given position. StringBuffer class has various forms of this method we will discuss it later.

class ExampleOfStringBuffer
{  
	public static void main(String args[])
	{  
		// creating a StringBuffer with specified string
                StringBuffer name = new StringBuffer("Ravi"); 
                // inserting string in string buffer
		name.insert(4, "kant"); 
		System.out.println("Name of Student = "+ name);		
	}
}  

Output: Name of Student = Ravikant

3. replace(startIndex, endIndex, string) method: This method is used to replace the string by given text. The replace() replaces the given string from the specified startIndex and endIndex.

class ExampleOfStringBuffer
{  
	public static void main(String args[])
	{  
		// creating a StringBuffer with specified string
		StringBuffer name = new StringBuffer("Ravi kant"); 
		name.replace(5, 7, "OK");
		System.out.println("Name of Student = "+ name);	
        }
}

Output: Name of Student = Ravi OKnt

Leave a Comment