Signup/Sign In
PUBLISHED ON: FEBRUARY 26, 2021

StringWriter append() Method in Java

In this tutorial, we will learn about append() method of StringWriter class in Java. This method is used to append the CharSequence to the existing StringWriter, this method comes in three other overloading methods to provide the flexibility of slice the CharSequence and write accordingly.

Syntax

This is the syntax declaration of the append() method, this method accepts CharSequence as a parameter and returns StringWriter.

public StringWriter append(CharSequence csq)

Example 1

In this example, we are implementing we are using the append() method that accepts a character only and appends it to the writer.

import java.io.IOException;
import java.io.StringWriter;
class StudyTonight
{
	public static void main(String[] args) throws IOException 
	{ 
		StringWriter stringWriter = new StringWriter();
		stringWriter.append('A');
		System.out.println("" + stringWriter.toString());
	} 
}


A

Example 2

Here, in this example, we are implementing another append() method of StringWriter class, this method accepts the CharSequence and appends it to the existing writer, here we can see the written CharSequence inside the StringWriter using the toString() method.

import java.io.*;  
public class StudyTonight
{  
	public static void main(String[] args) 
	{  
		CharSequence csq1="study";  
		CharSequence csq2="tonight";  
		StringWriter printWriter=new StringWriter();  
		printWriter.append(csq1);  
		printWriter.append(csq2);  
		System.out.println(printWriter.toString());
	}  
}  


studytonight

Example 3

Here, we are implementing another overloading method of append() method, this method accepts three parameters, CharSequence which is the source of data, start index, and end index specifying the range of the CharSequence, and then it will append it to the StringWriter.

import java.io.IOException;
import java.io.StringWriter;
class StudyTonight
{
	public static void main(String[] args) throws IOException 
	{ 
		StringWriter stringWriter = new StringWriter();
		CharSequence charSequence = "Hello Studytonight";
		stringWriter.append(charSequence, 0, 5);
		System.out.println("" + stringWriter.toString());
	} 
}


Hello

Conclusion

In this tutorial, we learned about the append() method of StringWriter class. This method is used to append the CharSequence to the existing StringWriter.



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.