Java - StringWriter append(char c) method



Description

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

Declaration

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

public StringWriter append(char c)

Parameters

c − The 16-bit character to append.

Return Value

This method returns this writer.

Exception

NA

Example - Usage of StringWriter append(char c) method

The following example shows the usage of StringWriter append(char c) 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();

      // append a char       
      System.out.println("" + sw.append("a"));
      System.out.println("" + sw.append("b"));
   }
}

Output

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

a
ab

Example - Appending a Single Character

The following example shows the usage of StringWriter append(char c) 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.append('H');
      sw.append('i');

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

Output

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

Output: Hi

Explanation

  • Appends 'H' and 'i' one by one to the StringWriter.

  • The resulting output is "Hi".

Example - Using append in a Loop to Build a String

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

StringWriterDemo.java

package com.tutorialspoint;

import java.io.StringWriter;

public class StringWriterDemo {
   public static void main(String[] args) {
      StringWriter sw = new StringWriter();

      for (char c = 'A'; c <= 'E'; c++) {
         sw.append(c);
      }

      System.out.println("Alphabets: " + sw.toString());
   }
}

Output

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

Alphabets: ABCDE

Explanation

  • A loop appends characters from 'A' to 'E' using the append(char c) method.

  • The final string becomes "ABCDE".

java_io_stringwriter.htm
Advertisements