Java - Writer append(char c) method



Description

The Java Writer append(char c) method appends the specified character to this writer.

Declaration

Following is the declaration for java.io.Writer.append(char c) method.

public Writer append(char c)

Parameters

c − The 16-bit character to append.

Return Value

This method returns the current writer.

Exception

IOException − If an I/O error occurs.

Example - Usage of Writer append(char c) method

The following example shows the usage of Writer append(char c) method.

WriterDemo.java

package com.tutorialspoint;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;

public class WriterDemo {
   public static void main(String[] args) {
      char c = 'A';

      // create a new writer
      Writer writer = new PrintWriter(System.out);

      try {
         // append a char
         writer.append('c');

         // append a new char
         writer.append(c);

         // flush the writer to see the result
         writer.flush();

      } catch (IOException ex) {
         ex.printStackTrace();
      }
   }
}

Output

Let us compile and run the above program, this will produce the following result −

cA

Example - Using StringWriter to Append Characters

The following example shows the usage of Writer append(char c) method.

WriterDemo.java

package com.tutorialspoint;

import java.io.StringWriter;

public class WriterDemo {
   public static void main(String[] args) {
      StringWriter writer = new StringWriter();
      writer.append('H');
      writer.append('i');
      writer.append('!');

      System.out.println("Output: " + writer.toString());
   }
}

Output

Let us compile and run the above program, this will produce the following result−

Output: Hi!

Explanation

  • Each append(char) call adds a single character.

  • "H" + "i" + "!" = "Hi!" is stored in the writer.

Example - Append Characters in a Loop

The following example shows the usage of Writer append(char c) method.

WriterDemo.java

package com.tutorialspoint;

import java.io.StringWriter;

public class WriterDemo {
   public static void main(String[] args) {
      StringWriter writer = new StringWriter();
      char[] chars = {'J', 'A', 'V', 'A'};

      for (char ch : chars) {
         writer.append(ch);
      }

      System.out.println("Result: " + writer.toString());
   }
}

Output

Let us compile and run the above program, this will produce the following result−

Result: JAVA

Explanation

  • A loop appends each character in the array to the StringWriter.

  • The final string becomes "JAVA".

java_io_writer.htm
Advertisements