Java - StringWriter toString() method
Description
The Java StringWriter toString() method returns the buffer's current value as a string.
Declaration
Following is the declaration for java.io.StringWriter.toString() method.
public String toString()
Parameters
NA
Return Value
This method returns a string representation of the object.
Exception
NA
Example - Usage of StringWriter toString() method
The following example shows the usage of StringWriter toString() method.
StringWriterDemo.java
package com.tutorialspoint;
import java.io.StringWriter;
public class StringWriterDemo {
public static void main(String[] args) {
// create a new writer
StringWriter sw = new StringWriter();
// write a string
sw.write("Hello World");
// print result by converting to string
System.out.println("" + sw.toString());
}
}
Output
Let us compile and run the above program, this will produce the following result −
Hello World
Example - Converting written text to String
The following example shows the usage of StringWriter toString() method.
StringWriterDemo.java
package com.tutorialspoint;
import java.io.StringWriter;
public class StringWriterDemo {
public static void main(String[] args) throws Exception {
StringWriter sw = new StringWriter();
sw.write("Welcome ");
sw.write("to Java!");
String result = sw.toString();
System.out.println("Output: " + result);
}
}
Output
Let us compile and run the above program, this will produce the following result−
Output: Welcome to Java!
Explanation
Text is written using write(...) methods.
toString() is called to retrieve the full content.
Example - Using toString() after modifying the buffer
The following example shows the usage of StringWriter toString() method.
StringWriterDemo.java
package com.tutorialspoint;
import java.io.StringWriter;
public class StringWriterDemo {
public static void main(String[] args) {
StringWriter sw = new StringWriter();
sw.write("Stream");
// Modify internal buffer directly
sw.getBuffer().append(" Writer");
// Convert to String
String result = sw.toString();
System.out.println("Output: " + result);
}
}
Output
Let us compile and run the above program, this will produce the following result−
Output: Stream Writer
Explanation
getBuffer() is used to directly modify the internal StringBuffer.
toString() then returns the updated content.