×

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

How to make Java Projects

Ant and Maven are both offered by NetBeans for the development of Java applications. When using Ant, the IDE creates an Ant build script depending on the settings you select...

6 minutes read.

Java.sql.Time Format

In JDBC API as a cover aroundjava.util.Date that handles SQL-specific requirements we use the java.sql.Time. The java.sql.Time extends java.util.Date class. To represent SQL TIME, without a date this class is...

6 minutes read.

Arithmetic exception in Java

Exception Handling is one of the most potent ways of handling runtime faults and preserving the application's normal flow. In Java, an exception is an out-of-the-ordinary state, and exceptions are...

3 minutes read.

Model Class in Java

In this section, we will be acknowledged about the model class in Java, its purpose and its uses. Also, we will learn how is this created and leveraged in java. Model...

4 minutes read.

How to check the Java version in cmd

To make programs that can run on our systems, we need to install programming language-related software in our systems. Different programming languages require different types of software, aka IDEs (Integrated...

5 minutes read.

Java Thread Dump Analyzer

Thread: A thread is a PC program that is stacked into the PC's memory and is under execution. It tends to be executed by a processor or a bunch of processors....

15 minutes read.

Find Unique Elements in Array Java

An array in Java is a grouping of objects that share the same type of data. We are free to enter identical or repeating elements into an array. Therefore, we...

6 minutes read.

Java Math cosh() Method

The cosh() method of Math class returns the first hyperbolic cosine((e+e)/2) of a double value. Syntax: public static double cosh(double x) Parameters: The parameter ‘x’ represents the number whose hyperbolic cosine is to be...

2 minutes read.

Balanced Parentheses in Java

One of the frequent programming issues, commonly referred to as the Balanced brackets issue, is the problem with the balanced parenthesis. Interviewers frequently provide this task, in which we must...

5 minutes read.

List of Constants in Java

In this tutorial, we are going to deal with constants available in Java.Every programming language has its constants. Similarly, Javaalso has got constants of its own. In this tutorial, we will...

6 minutes read.

Java Architecture

Java architecture is a combination of three parts they are JVM, JRE and JDK. These components will help in the functioning of the java programs. The process of code interpretation...

6 minutes read.

Balanced Prime Number in Java

This section will cover the definition of a balanced prime number as well as how to find one using a Java program. Balance Prime Number A prime number that is equivalent to...

5 minutes read.

Beautiful Array in Java

In this section, we will be acknowledged about the beautiful array in Java, its characteristics, how it is achieved. What are the types of approaches and what are the tools...

8 minutes read.

Java Iterator

When iterating through, traversing, or retrieving the individual elements of a Collection or Flow object, a Java Cursor is leveraged as an iterator. In Java, there exist three types of...

4 minutes read.

How to calculate time complexity of any program in Java

Java : Java's syntax and principles are derived from the C and C++ languages. We know that java is one of the programming language. The main feature of java which is...

3 minutes read.

How to set path in Java

To make programs that can run on our systems, we need to install programming language-related software in our systems. Different programming languages require different types of software, aka IDEs (Integrated Development...

5 minutes read.

Binary Strings Without Consecutive Ones in Java

N, an integer, is provided. Our objective is to determine the overall number of strings with length N that do not include successive 1s. Example: Input: 3 Output: 6 Explanation The binary forms of length...

6 minutes read.

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.

Java String compareTo() Method

compareTo() method is used to compare the two specified Strings based on the alphabetical order(lexicographical order) of their characters.It returns positive number ,negative number or 0 Syntax: public int compareTo(String anotherString) Parameters: anotherString: the...

2 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.