Java - StringWriter write(int c) method
Description
The Java StringWriter write(int c) method writes a single character.
Declaration
Following is the declaration for java.io.StringWriter.write(int c) method.
public void write(int c)
Parameters
c − int specifying a character to be written.
Return Value
This method does not return a value.
Exception
NA
Example - Usage of StringWriter write(int c) method
The following example shows the usage of StringWriter write(int c) method.
StringWriterDemo.java
package com.tutorialspoint;
import java.io.StringWriter;
public class StringWriterDemo {
public static void main(String[] args) {
// create a new writer
StringWriter sw = new StringWriter();
// write integers that correspond to ascii code
sw.write(70);
sw.write(76);
// print result by converting to string
System.out.println("" + sw.toString());
}
}
Output
Let us compile and run the above program, this will produce the following result −
FL
Example - Writing a Single Character
The following example shows the usage of StringWriter write(int c) method.
StringWriterDemo.java
package com.tutorialspoint;
import java.io.StringWriter;
public class StringWriterDemo {
public static void main(String[] args) {
StringWriter writer = new StringWriter();
// Writing a single character using its Unicode value
writer.write(72); // 'H' in Unicode
writer.write(101); // 'e'
writer.write(108); // 'l'
writer.write(108); // 'l'
writer.write(111); // 'o'
String result = writer.toString();
System.out.println(result); // Output: Hello
}
}
Output
Let us compile and run the above program, this will produce the following result−
Hello
Explanation
A StringWriter is created.
write(int c) is called multiple times with Unicode values −
72 → H
101 → e
108 → l
108 → l
111 → o
toString() converts the buffer into "Hello".
Example - Writing Special Characters & Newlines
The following example shows the usage of StringWriter write(int c) method.
StringWriterDemo.java
package com.tutorialspoint;
import java.io.StringWriter;
public class StringWriterDemo {
public static void main(String[] args) {
StringWriter writer = new StringWriter();
// Writing special characters
writer.write(65); // 'A'
writer.write(10); // '\n' (newline)
writer.write(33); // '!'
String result = writer.toString();
System.out.println(result);
}
}
Output
Let us compile and run the above program, this will produce the following result−
A !
Explanation
write(int c) is called multiple times with Unicode values−
65 → 'A'
10 → '\n' (newline character)
33 → '!'
The final string is printed with a newline and special characters.