×

Java StringWriter Class

The StringWriter class is a character stream in which it is used to store the output consisting of characters into the string buffer. Upon collecting output into a string buffer, a string is further constructed.

The string buffer in java is a mutable string that means it can be modified.

Java StringWriter class allows you to get the characters written to the writer as a whole string.

The StringWriter class is used if we want the data as a whole string or if you have a component that consists of characters that can only write data to a writer, but you want the data to be a string.

After finishing writing characters to the java StringWriter, we can always choose to close the string buffer stream. But the String writer class is not connected to any system resources like network connections or other forces,it is not always important to close the stream.

Package

The Java StringWriter class is available in the java.io package. To use this String Writer class, the java.io.StringWriter package needs to be imported.

In java IO classes, the super class of string writer is Writer class and the super class of this Writer class is object class. Using string writer classes, closeable, auto-closeable, appendable, and flushable interfaces are implemented.

Constructor

The string writer class supports two types of constructors, one for default and one for finding the initial size of the string buffer. They are 

  1. StringWriter() – it is a default constructor and takes the default initial size of string buffer to create a new string writer
  2. StringWriter(int initialsize) – this constructor is used for creating a new string writer by taking a specific initial size of string buffer.

Methods

Different types of methods present in Writer class are implemented using the StringWriter class. Few methods are mentioned below.

String() methods

  • String toString() –  for converting the string buffer present available current value as a string 
  • StringBuffer getBuffer() –to get string buffer this particular method can be used

Append() methods

  • StringWriter append(CharSequence csq) –for appending the particular character sequence to the writer
  • StringWriter append(char c) – same as the above method, but this method is used for appending only characters to the writer

Write() methods

  • Write()- for writing only a single character to the writer, write () method is helpful
  • Write(char[] array)- this method is used for writing specific characters present in an array to the writer
  • Write(String data) – a specified whole string is written to the writer in this method 

Other methods

  • Void close() -this method is for closing the stream
  • Void flush()- this method is for flushing the stream. That means the data present in the writer is forced into the string buffer.

Declaration of StringWriter class

The writer class is extended by a string writer class. The declaration of string writer class can be given as:

public class StringWriter extends Writer

Creation of StringWriter class

To create a string writer class, the java.io.StringWriter package needs to be imported in the first place. Once the package is imported, then the class can be implemented in the below following two cases.

  • With default initial buffer size
 StringWriter result  =  new StringWriter();
  • With initial size of string buffer
 StringWriter result  =  new StringWriter(int size);

Example Java Program for StringWriter class:

// This program is for demonstrating a String Writer class
// import the package
Import java.io. *;
Import java.io.StringWriter;
Public class StringDemo
{
Public static void main(String s [])
{
// Creation of string writer class
StringWriter charStream = new StringWriter (); 
// Creation of print writer class
PrintWriter outputStream = new PrintWriter (charStream);
String s1 = “My name is tony stark ”; // declare any string s1
String s2 = “I am Avengers team”; // declare any string s2
Int num = 5; // take some integer value
// Now print the string sequence using the output stream object
outputStream. print( s1 + “ “ + s2 + “ “ + “we are fantastic ” + num ); 
String result = charStream. toString(); // assign result
System. out. println (result); // print result
}
}

Output:

My name is tony stark I am Avengers team we are fantastic 5

The above result shows us how the data is taken from the file and converted into a string using the toString() method. StringWriter class collects the output from the outputstream and stores it in string buffer, then joins to construct a string.


Related Topics

Internal Working of ArrayList in Java

Java's version of a resizable array is called ArrayList. The dynamic growth of an array list ensures that there is always room for new elements. ArrayList's backing data structure is...

8 minutes read.

Bifunction in java 8

A functional interface in Java is called BiFunction. It first appeared in Java 8. It can serve as the assigning target for a method reference or lambda expression. The java.util.function...

4 minutes read.

User Defined Exception in Java

An exception is an error (run time error) that happened while a program was being executed. The program stops abruptly whenever the Exception occurs, and the code after the line...

3 minutes read.

Access modifiers in Java

Access modifiers in Java with Example In Java, there are two types of access modifiers one is a non-access modifier, and other is access modifier. If we talk about access modifier, there...

3 minutes read.

Java Integer toBinaryString() method

The toBinaryString() method of Java Integer class returns a string representing the specified int argument as an unsigned integer in base 2. Syntax public static String toBinaryString (int  i)  Parameters The parameter ‘i’ represents...

1 minute read.

Java Anon Proxy

The Java Anon Proxy (JAP), also known as JonDonym, is a proxy system designed to enable Web browsing with revocable (the use of or publication under a pseudonym, a false...

4 minutes read.

Type Annotations in Java

Only declarations were eligible for annotations in earlier versions of Java. With Java 8, you may now annotate any type use, including types in declarations, generics, and casts: @Encrypted String data; List<@NonNull...

6 minutes read.

Advanced Java skills

These were some of the contemporary talents that a Java developer should master in efforts to progress in the era of science in 2022. A database such as MySQL, a...

4 minutes read.

String Palindrome Program in Java

String Palindrome Program in Java The palindrome is a string, phrase, word, number, or other sequences of characters that can be read in both directions i.e. forward (left to right) and...

11 minutes read.

Non-primitive data types in Java

The kind of data stored in the variable is determined by its type. The type describes the data category (different sizes and values). These are not already built into the devices....

4 minutes read.

Java Variable Declaration

In this article, you will be acknowledged about java variable declaration. You will be able to learn and interpret about declaring a variable in Java. Variable in Java Variables are necessary for...

6 minutes read.

Constructor Overloading in Java

In Java, constructors can be overloaded just like methods. The idea of having multiple constructors with various parameter sets so that each function Object()  can carry out a particular task...

3 minutes read.

Java Math cbrt() Method

The cbrt() method of Math class returns the cube root of a double value. Syntax: public static double cbrt(double a) Parameters: The parameter ‘a’ represents the value whose cube root is to be determined. Return...

2 minutes read.

Enterprise Java Beans

One of the many Java APIs for the common development of corporate software is Enterprise Java Beans (EJB). An EJB, a server-side software component, contains the business logic of an...

4 minutes read.

Java Enum Keyword

Definition: A data type in Java called Enum has a respect to supply of constants. The weekdays (SUN, MON, TUE, WED, THU, FRI, and SAT), directions (NORTH, SOUTH, EAST, and WEST),...

4 minutes read.

Fork Join in Java

Multithreaded processors are being introduced in new computer systems today. The operation is faster due to multicore CPUs. Therefore, it becomes essential for a programmer to leverage multithreaded processors effectively...

4 minutes read.

Why to use Enum in Java?

In this article, you will be acknowledged about the Enum in java, its uses and mainly its purpose. Enum has various functionalities. Each of them will be discussed. Enum In a computer...

3 minutes read.

Java String isEmpty() method

Java String isEmpty() method checks whether current String is empty or not. Syntax: public boolean isEmpty() Returns It returns true, if length of String is 0 otherwise false. Java String isEmpty() method example 1    ...

1 minute read.

Bottom view of a binary tree in Java

The lowest nodes in their horizontal distance are present and referred to as the bottom view of a binary tree. The horizontal distance between the nodes of a binary tree...

4 minutes read.

Java 8 Consumer Interface in Java

The Consumer Interface is used to implement the functional programming in Java. The Consumer Interface indicates a function that accepts a single input and outputs a result. These functions don’t...

2 minutes read.