java.lang.StringBuffer append(char c)

Description :

This java tutorial shows how to use the append(char c) method of StringBuffer class under java.lang package. The append method of StringBuffer class is overloaded which takes different data type as input however on this case the input is character data type thus the base string is appended with the string representation of the character input.

Method Syntax :

public StringBuffer append(char c)

Parameter Input :

DataType Parameter Description
char c This is the character value to be converted to character sequence which will be appended on the base string.

Method Returns :

The append(char c) method simply returns the reference object which is the combined String representation of the base string and the character method input.

Compatibility Version :

Requires Java 1.0 and up

Discussion :

The append method is overloaded thus this method can generally takes different data types however on this case it is character. Technically speaking the char c method argument is converted using the static method String.valueOf(char b).

It would also be interesting to know that the equivalent string after calling the append(char c) method would be StringBuffer.toString() + “char c”.

Java Code Example :

This java example source code demonstrates the use of append(char c) method of StringBuffer class. Basically this code just takes a user input and then the program will append the character input to the original String on the buffer. This source code is a good example in learning on how to initialize StringBuffer object, modify the contents of the StringBuffer object and printing of the current String on the buffer.

package com.javatutorialhq.java.examples;

import static java.lang.System.*;

import java.io.IOException;
import java.util.Scanner;

/*
 * This example source code demonstrates the use of append(char c)
 * of StringBuffer class
 */

public class StringBufferAppendChar {

	public static void main(String[] args) throws IOException {
		
		String name = "Andrew";
		char gender;
		
		// initialize the StringBuffer object
		StringBuffer sb = new StringBuffer(name+"|");
		// ask for user input
		System.out.print("Enter your gender(M/F):");		
		gender = (char) System.in.read();		
		sb.append(gender);
		System.out.println(sb);

	}

}

Sample Output :

Running the append(boolean b) method example source code of StringBuffer class will give you the following output

Enter your gender(M/F):M
Andrew|M

Exception Scenario :

N/A

Similar Method :

  • N/A

Suggested Reading List :

References :