Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PrintWriter write() vs print() method in Java [duplicate]

Tags:

java

file

What is the difference between write() and print() methods in PrintWriter class in Java?

like image 790
Sasikumar Murugesan Avatar asked Jun 05 '15 09:06

Sasikumar Murugesan


People also ask

What does PrintWriter print do?

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.

Where does PrintWriter write to?

You create the print writer pointing to the system out stream.

Does PrintWriter overwrite?

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.

What is the method that writes a string using a PrintWriter?

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.


2 Answers

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

like image 128
Maantje Avatar answered Sep 24 '22 19:09

Maantje


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.

like image 41
Anindya Dutta Avatar answered Sep 23 '22 19:09

Anindya Dutta