Signup/Sign In
LAST UPDATED: MARCH 1, 2021

CharArrayWriter toCharArray() method in Java

In this tutorial, we will learn about the toCharArray() method in Java. This method is available in java.io package This method returns the array of characters from the stream. This method is a non-static method so we must need to create an object to call this method.

Syntax

This is the syntax of the toCharArray() method, this method does not accept any parameter but returns the char array.

public char[] toCharArray();

enlightened Here is an interesting point to note, the toCharArray() method does not throw an exception while converting a CharacterWriterArray to a character array.

Example of toCharArray() Method

In this example, we have an array of characters and we append it to the CharArrayWriter. After writing it to the CharArrayEriter we can simply convert it to an array of char using the toCharArray() method and it will return an array of characters.

import java.io.CharArrayWriter;
import java.io.IOException;
public class StudyTonight 
{
	public static void main(String[] args) throws IOException 
	{ 
		CharArrayWriter writer = new CharArrayWriter(); 
		char[] myText = { 'H', 'E', 'L', 'L', 'O' }; 
		for (char c : myText)
		{ 
			writer.append(c); 
		} 
		char[] arr = writer.toCharArray();
		System.out.print("toCharArray : ");
		for (char c : arr) 
		{ 
			System.out.print(" " + c); 
		}
	} 
}


toCharArray : H E L L O

Example of toCharArray() method:

In this example, we are converting given CharArrayWriter to the array of characters same as the above example but the difference is we created CharArrayWriter with the appending CharSequence and still it works well so we can draw the conclusion that the toCharArray() method will convert the given CharArrayWriter to the character array in all the situations.

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);

		char[] arr = charArrayWriter.toCharArray();
		System.out.print("toCharArray : ");
		for (char c : arr) 
		{ 
			System.out.print(" " + c); 
		}
	}   
}


toCharArray : s t u d y t o n i g h t

Conclusion:

In this tutorial, we learned about the CharArrayWriter toCharArray() method in Java. This method returns the array of characters from the stream. This method is used to convert the CharacaterWriterArray stream to a character array.



About the author:
I am the founder of Studytonight. I like writing content about C/C++, DBMS, Java, Docker, general How-tos, Linux, PHP, Java, Go lang, Cloud, and Web development. I have 10 years of diverse experience in software development.