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

CharArrayWriter toString() Method in Java

In this tutorial, we will learn about toString() method of CharArrayWriter class in Java. This method belongs to the java.io package. This method is used to represent the buffer data as a string from this CharArrayWriter stream. This method does not throw an exception at the time of string representation of the stream.

Syntax

This is the declaration syntax of the toString() method in Java. It does not accept any parameter. The return type of the method is String, it returns the existing buffer data as a string

public String toString();

Example of toString() Method

In this example, we are writing the arr to the CharArrayWriter using the write method and then we are getting it as a stream. This method is used to represent the buffer data as a string from this CharArrayWriter stream.

import java.io.CharArrayWriter;
public class StudyTonight 
{
	public static void main(String[] args) throws Exception 
	{  
		char[] arr = { 's', 't', 'u','d', 'y', 't' ,'o' ,'n' ,'i' ,'g', 'h', 't' };  
		CharArrayWriter charArrayWriter = new CharArrayWriter();  
		charArrayWriter.write(arr);  
		String str = charArrayWriter.toString();  
		System.out.print(str);  
	}    
}


studytonight

Example of toString() Method

This is another example of demonstrating a toString() method. In this example, we are writing the data to the CharArrayWriter using the append method, we passed two strings using the append method and it is returning it. This method is used to represent the buffer data as a string from this CharArrayWriter stream.

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

		CharSequence sequence1 = "study";
		CharSequence sequence2 = "tonight";

		charArrayWriter.append(sequence1);
		charArrayWriter.append(sequence2);

		System.out.println("String: "	+ charArrayWriter.toString());
	}   
}


String: studytonight

Conclusion:

In this tutorial, we learned about the toString() method CharArrayWriter toString() method in Java, This method is used to represent the buffer data as a string from this CharArrayWriter stream. This method does not throw an exception at the time of string representation of the stream.