×

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

Java Binary to Hexadecimal

Converting between types in programming is an important task. Moving from one kind to another kind conversion is occasionally necessary. We have discussed numerous conversion types in the section on...

3 minutes read.

Various Operation on Queue using Linked List in Java

We keep track of front and rear pointers in a queue data structure. The head of the line points to the first item, and the back to the last. Rear is...

3 minutes read.

Java Math pow() Method

The pow() method of Math class returns the value of first argument raised to the power of second argument i.e. ab. Syntax: public static double pow(double a, double b) Parameters: The parameters ‘a’ and...

3 minutes read.

Iterate JSON array in Java

This article is going to equip the knowledge about what JSON array is and how it works and also how is it distinct with the generic array. Json Array Ordered lists of...

4 minutes read.

How to Split String by Comma in Java

strsplit() technique permits you to break a string given the explicit Java string delimiter. The Java string split property is frequently a space or a comma(,) that you want to...

7 minutes read.

Sales Tax Problem in Java

To calculate the sales tax on a purchase in Java, you will need to know the following information: The cost of the item being purchased The sales tax rate You can then use...

4 minutes read.

Tetris Game in Java

The Tetris game is among the most well-known video games ever produced for computers. Today, we may engage in this game on a mobile device as well. Alexey Pajitnov conceptualized...

12 minutes read.

How to Convert Timestamp to Date in Java

How to Convert Timestamp to Date in Java You can convert Timestamp to Date by using the constructor of Date class. It returns the long millisecond from Epoch (1st January 1970)...

2 minutes read.

Decagonal Numbers in Java

This section explains what is a decagonal number and how to write Java programmes that compute decagonal numbers. Both academics and Java programmer interviews regularly question about the Decagonal number...

3 minutes read.

Java Error Stack Trace

The stack trace in Java is an array of stacks.The stack trace reveals the console's location of an exception or error by gathering data from all program methods. The JVM...

3 minutes read.

Java logger

Logging is a crucial Java feature that aids developers in identifying issues. The logging methodology is included with Java as the programming language. It offers the Logging API, which debuted...

7 minutes read.

Properties Class in Java

Properties class is associated with Java since JDK 1.0, i.e. it is a legacy class. It is the subclass of Hashtable. It is used to maintain the lists of values in which...

5 minutes read.

Static vs Non-Static in Java

A static method can access and update the value of a static data member. The static keyword is mostly used in Java for memory management. The static keyword can be...

6 minutes read.

How to compare two dates in different format in Java?

We need to compare two dates frequently when coding. Real-world examples include sorting a list of persons by age or keeping track of students' attendance. To compare two dates, we...

7 minutes read.

Java String startsWith() method

Java String startsWith() method checks whether current String starts with given prefix or not . Syntax: public boolean startsWith(String prefix) public boolean startsWith(String prefix, int offset) Parameters: prefix : It is sequence of character Returns: It returns...

2 minutes read.

HashMap Vs HashTable

HashMap HashMap is the basic implementation of the map interface in Java. HashMap stores the data in key and value pairs. Keys are used to access the value of the element. It...

5 minutes read.

Insertion Sort in Java

Insertion Sort in Java Insertion sort in Java is a simple sorting algorithm that works in the same way as we hold cards in hand. Insertion sort does the sorting element-by-element,...

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

Constructor in Java with Example

Java Constructor  The constructor is used for object initialization. It's a block of code that initializes a newly created object. It contains a collection of statements that are executed at the...

5 minutes read.

How to Convert double to int in Java

The double is a larger data type than int. When we assign a larger type value to a variable of smaller type, then we need to perform the explicit conversion....

2 minutes read.