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

StringWriter flush() method in Java

In this tutorial, we will learn about the flush() method of StringWriter class in Java. This method is used to flush the writer, which means that this method will remove all the data present inside the writer. It neither accepts any parameter nor returns any value.

Syntax

This is the syntax declaration of the flush() method, this method does not take any parameter as input and does not return anything as it's return type is void.

public void flush()

Example 1

In the following example, we are implementing how the flush() method works, this method is used to remove the written data from the writer, here we have written the data to the writer and after that, we are flushing it by calling the flush() method.

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

		String str = "Hello Studytonight";

		stringWriter.write(str);

		stringWriter.flush();

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


Hello Studytonight

Example 2

Here, we are implementing the example of a flush() method to clear the writer. Once we have written the data into it we call the flush method. This method is used to flush the writer, which means that this method will remove all the data present inside the writer.

import java.io.IOException;
import java.io.StringWriter;
class StudyTonight
{
	public static void main(String[] args) throws IOException 
	{ 
		try
		{ 
			StringWriter writer = new StringWriter(); 
			writer.write(65); 
			System.out.println(writer.toString()); 
			writer.flush(); 
		} 
		catch (Exception e)
		{ 
			System.out.println(e); 
		} 
	} 
}


A

Conclusion

In this tutorial, we learned about the flush() method of StringWriter class in Java. This method is used to flush the writer, which means that this method will remove all the data present inside the writer. It neither accepts any parameter nor returns any value.