What is the difference between write()
and print()
methods in PrintWriter
class in Java?
Class PrintWriter. Prints formatted representations of objects to a text-output stream. This class implements all of the print methods found in PrintStream . It does not contain methods for writing raw bytes, for which a program should use unencoded byte streams.
You create the print writer pointing to the system out stream.
In our first example, we'll use PrintWriter to create a new file by passing in the filename to its constructor as a string. If the file doesn't exists, it will be created. If it already exists, it will be overwritten and all its contents will be lost.
The write(String) method of PrintWriter Class in Java is used to write the specified String on the stream. This String value is taken as a parameter. Parameters: This method accepts a mandatory parameter string which is the String to be written in the Stream. Return Value: This method do not returns any value.
print() formats the output, while write() just prints the characters it is given. print() handles many argument types, converting them into printable strings of characters with String.valueOf(), while write() just handles single characters, arrays of characters, and strings.
To illustrate the difference, write(int) interprets the argument as a single character to be printed, while print(int) converts the integer into a character string. write(49) prints a "1", while print(49) prints "49".
source: http://www.coderanch.com/t/398792/java/java/write-print
write(int)
writes a single character (hence takes the Unicode character of the passed int
).
print(datatype)
on the other hand converts the datatype (int
, char
, etc) to a String by first calling String.valueOf(int)
or String.valueOf(char)
which is translated into bytes according to the platform's default character encoding, and these bytes are written in exactly the manner of the write(int)
method.
For more details, you can refer the documentation of PrintWriter
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With