Lesson 3 | Using PrintWriter |
Objective | Familiarize yourself with how to use PrintWriter. |
Using Java PrintWriters
There are four constructors in the
PrintWriter
class.
public PrintWriter(Writer out)
public PrintWriter(Writer out, boolean autoFlush)
public PrintWriter(OutputStream out)
public PrintWriter(OutputStream out,
boolean autoFlush)
The
PrintWriter
can either send data to an
OutputStream
or to another writer.
If
autoFlush
is set to true, the
PrintWriter
is flushed every time the
println()
method is invoked.
The PrintWriter API has not changed in terms of these four constructors since Java 1.1.
These constructors have remained the same in Java 1.1 through Java 22, ensuring backward compatibility.
Historical Context
- The
PrintWriter
class was introduced in Java 1.1 (1997) as part of the java.io
package.
- The four constructors you listed have been present since Java 1.1 and continue to exist in modern Java versions (e.g., Java 22).
- They provide different ways to initialize a
PrintWriter
object using either a Writer
or an OutputStream
, with an optional autoFlush behavior.
Current Status in Java 22
In Java SE 22, the PrintWriter class still has these same four constructors, along with additional constructors that were introduced later:
Conclusion: The four constructors in your question have been present since Java 1.1 and have not changed in Java 22. However, newer constructors were added in later Java versions to enhance file handling and encoding support.
print( ) and println( ) Methods in the PrintWriter Class
The main advantages of the
PrintWriter
class are the overloaded methods. The print method is overloaded 9 times
in the PrintWriter Class.
The PrintWriter class in Java provides several overloaded print() methods to handle different data types, which makes it very versatile for output operations. Here are the 9 overloaded versions of the print() method in the PrintWriter class:
print(boolean b)
- Prints a boolean value.
print(char c)
- Prints a single character.
print(char[] s)
- Prints an array of characters.
print(double d)
- Prints a double value.
print(float f)
- Prints a float value.
print(int i)
- Prints an integer value.
print(long l)
- Prints a long value.
print(Object obj)
- Prints an object's string representation by calling its toString()
method.
print(String s)
- Prints a string.
These overloaded methods allow developers to write code that's more readable and type-specific, reducing the need for explicit type conversion when writing to files or streams. This design enhances both the efficiency and the simplicity of I/O operations in Java.
PrintWriter println() Methods which are overloaded in the PrinterWriter Class
-
Overloaded Methods: The PrintWriter class indeed has several overloaded methods, including
println()
. Overloading allows methods with the same name to perform different operations based on the types and/or number of arguments passed to them.
-
Number of Overloads for println(): The
println()
method in PrintWriter is actually overloaded more than 10 times. Here's a breakdown:
println()
- Prints a new line to the output stream.
println(boolean x)
- Prints the boolean value x
followed by a new line.
println(char x)
- Prints the character x
followed by a new line.
println(int x)
- Prints the integer value x
followed by a new line.
println(long x)
- Prints the long integer value x
followed by a new line.
println(float x)
- Prints the floating-point value x
followed by a new line.
println(double x)
- Prints the double-precision floating-point value x
followed by a new line.
println(char[] x)
- Prints the character array x
followed by a new line.
println(String x)
- Prints the string x
followed by a new line.
println(Object x)
- Prints the string representation of the object x
(using String.valueOf(x)
) followed by a new line.
Additionally, there are variations for each of these with different types of Appendable, File, OutputStream, etc., for constructors, but for println() itself, there are at least 10 versions directly related to primitive types and common reference types, plus additional ones for handling Throwable and formatting (printf style), though not strictly println overloads.
This flexibility allows developers to easily output different types of data without needing to explicitly convert them to strings or other types before printing, enhancing both readability and efficiency of code dealing with console or file output.
Here are the overloaded versions of the println() method in Java's PrintWriter class,
- No argument:
- Primitive types:
println(boolean x)
println(char x)
println(int x)
println(long x)
println(float x)
println(double x)
- Arrays and Strings:
println(char[] x)
println(String x)
- Object reference:
Additionally, although not directly part of the println set, there are other methods in PrintWriter that extend its functionality in ways similar to println for different data types:
- printf and format methods for formatted output:
printf(String format, Object... args)
format(String format, Object... args)
- Methods to print without a newline:
print(boolean x)
print(char x)
print(int x)
print(long x)
print(float x)
print(double x)
print(char[] x)
print(String x)
print(Object obj)
This list shows that there are more than 10 ways to call println() with different argument types, providing extensive flexibility for output operations in Java.
Any Java object, variable, or literal can be printed by passing it to a
print()
or
println()
method.
The
println()
method follows its argument with a platform-dependent line separator such as
\r\n
and then flushes the output if
autoFlush
is enabled. The
print()
method does not. Otherwise these methods are the same.
checkError( ) method
None of the methods of the
PrintWriter
class throw
IOException
s.
If any exceptions are thrown, they are caught inside the class. You can check to see whether any exceptions have been thrown with
checkError()
.
public boolean checkError()
This method returns true if an error has occurred and false if it hasn't. There's no easy way to determine exactly what the error was, though.
Other PrintWriter methods
The PrintWriter
class also contains other PrintWriter methods listed below.
Functions of the Java Methods in PrintWriter Class
The following methods belong to the PrintWriter class in Java, which is used for writing formatted text to an output stream.
1. public void flush()
2. public void close()
-
Function:
- Closes the
PrintWriter
and releases any system resources associated with it.
-
Behavior:
- Also calls
flush()
before closing.
- Once closed, further writing attempts result in an
IOException
.
-
Example:
3. public void write(int c)
-
Function:
- Writes a single character to the output stream.
-
Behavior:
- The integer is cast to a character before writing.
-
Example:
4. public void write(char buf[], int offset, int length)
-
Function:
- Writes a subset of a character array to the output.
-
Parameters:
buf[]
: The character array.
offset
: The starting position in the array.
length
: The number of characters to write.
-
Example:
-
PrintWriter writer = new PrintWriter(System.out);
char[] data = {'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd'};
writer.write(data, 6, 5); // Writes "World"
writer.flush();
5. public void write(char buf[])
- Function:
Writes an entire character array to the output.
- Example:
PrintWriter writer = new PrintWriter(System.out);
char[] data = {'H', 'e', 'l', 'l', 'o'};
writer.write(data); // Writes "Hello"
writer.flush();
6. public void write(String s, int offset, int length)
- Function:
- Writes a substring of a string to the output.
- Parameters:
s
: The string.
offset
: The starting position in the string.
length
: The number of characters to write.
- Example:
7. public void write(String s)
Summary Table:
Method |
Function |
flush() |
Forces buffered output to be written immediately. |
close() |
Closes the stream, flushing any remaining output. |
write(int c) |
Writes a single character. |
write(char buf[], int offset, int length) |
Writes a specific portion of a character array. |
write(char buf[]) |
Writes an entire character array. |
write(String s, int offset, int length) |
Writes a specific substring. |
write(String s) |
Writes an entire string. |
Each of these methods plays a crucial role in writing data efficiently to console, files, or network streams in Java!
The usual Writer
methods like write()
and flush()
, though it's rare to use them.
