PUBLISHED ON: FEBRUARY 26, 2021
StringWriter toString() method in Java
In this tutorial, we will learn about the toString()
method of StringWriter class in Java. This method is used to represent the buffer current value in terms of string. 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 toString() method, it does not accept any parameter and return a string.
public String toString();
Example 1
In this example, we will see how to use the toString()
method to get the data written to the StringWriter
. When we call the toString() method it will extract the current value of buffer and return in the form of a string.
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.toString());
}
}
Hello Studytonight
Example 2
Here in this example, we created an object of StringWriter class and then we call the toString() method to read the data of the buffer and it will return the value of buffer in string format.
import java.io.IOException;
import java.io.StringWriter;
class StudyTonight
{
public static void main(String[] args) throws IOException
{
try
{
StringWriter stringWriter = new StringWriter();
String string = "Hello Studytonight";
stringWriter.write(string);
System.out.println("String = "+ stringWriter.toString());
}
catch (Exception e)
{
System.out.println(e);
}
}
}
String = Hello Studytonight
Conclusion
In this tutorial, we learned about the toString()
method of StringWriter class in Java. This method is used to represent the buffer current value in terms of string.t 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.