Programming Tutorials

CharArrayWriter sample program in Java

By: Baski in Java Tutorials on 2022-09-15  

CharArrayWriter is a class in Java that extends the Writer abstract class and provides a buffer to write characters into an internal buffer which can later be used to create a String.

Here's an example program that uses CharArrayWriter:


public class CharArrayWriterExample {
    public static void main(String[] args) throws IOException {
        CharArrayWriter writer = new CharArrayWriter();
        String message = "Hello World!";
        char[] buffer = writer.toCharArray();
        System.out.println(new String(buffer));

The above program creates an instance of CharArrayWriter, writes the string "Hello World!" to it, and then converts the written characters into a character array using the toCharArray() method. Finally, the character array is printed as a String.

CharArrayWriter has two constructors:

  1. CharArrayWriter(): Creates a new CharArrayWriter with a default initial size of 32 characters.
  2. CharArrayWriter(int initialSize): Creates a new CharArrayWriter with an initial buffer size of initialSize.

Add Comment

* Required information


No comments yet. Be the first!

Most Viewed Articles (in Java )

Latest Articles (in Java)