Hurry! Try our new Interactive Courses for FREE. 🥳   🚀

StringWriter getBuffer() method in Java

In this tutorial, we will learn about the getBuffer() method of StringWriter class in Java. This method is used to get the StringBuffer that holds the present buffer value. This method is available in the java.io package. It is a non-static method, it is accessible with the class object only and if we try to access the method with the class name then we will get an error.

Syntax

This is the syntax declaration of the getBuffer() method, it does not accept any parameter and returns StringBuffer.

public StringBuffer getBuffer();

Example 1

In this example, we are implementing the getBuiffer() method of StringWriter class. Firstly we have written the text to the StringWriter using the write() method to verify that we are using the getBuffer() method and it will return the StringBuffer.;

import java.io.IOException;
import java.io.StringWriter;
class StudyTonight
{
	public static void main(String[] args) throws IOException 
	{ 
		StringWriter stringWriter = new StringWriter();

		stringWriter.write("Hello Studytonight");

		System.out.println("" + stringWriter.getBuffer());
	} 
}


Hello Studytonight

Example 2

Here is another example to illustrate how the getBuffer() method works. After writing the data to the StringWriter we call the getBuffer() method, this method will return the buffer hold by the corresponding StringWriter.

import java.io.IOException;
import java.io.StringWriter;
class StudyTonight
{
	public static void main(String[] args) throws IOException 
	{ 
		try
		{ 
			StringWriter writer = new StringWriter(); 
			String str = "Studytonight"; 
			writer.write(str); 
			StringBuffer stringBuffer = writer.getBuffer(); 

			System.out.println("StringBuffer = " + stringBuffer); 
		} 
		catch (Exception e) 
		{ 
			System.out.println(e); 
		} 
	} 
}


StringBuffer = Studytonight

Conclusion

In this tutorial, we learned about the getBuffer() method of StringWriter class in Java. This method is used to get the StringBuffer that holds the present buffer value. This method is available in the java.io package.