Win a copy of Cross-Platform Desktop Applications: Using Node, Electron, and NW.js this week in the JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Difference between print and write  RSS feed

Hari Haran
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
can anyone explain in detail the difference between print and write methods in the PrintWriter Class
Rahul Mahindrakar
Ranch Hand
Posts: 1869
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The print and write methods are defined as given below
print(boolean b) Print a boolean value.
print(char c) Print a character.
print(char[] s) Print an array of characters.
print(double d) Print a double-precision floating-point number.
print(float f) Print a floating-point number.
print(int i) Print an integer.
print(long l) Print a long integer.
print(Object obj) Print an object.
print(String s) Print a string.

write(char[] buf)Write an array of characters.
write(char[] buf, int off, int len)Write a portion of an array of characters.
write(int c)Write a single character.
write(String s)Write a string.
write(String s, int off, int len)
The write methods other than the abstract method write(char[] cbuf, int off, int len) are inherited from the abstract class Writer. The creators of the PrintWriter class wanted to add additional functionality through the print methods but did not use overloading the the write methods as they may want to demarcate between methods inhereted and methods in the PrintWriter class.
If the print methods were not available and if i wanted to print out the char 'A'then calling write(int i) would cast the char into an int and print out the ASCII value of 'A' rather than 'A'. similarly to print out a float or a double i would have to convert them to a String and then print it out.

Printing out a long would be a problem too as i have to either convert it to a string and then use write(String s) or have to cast it to an int and then use write(int i) but in the latter case there may be a loss of data.
Thus the two methods print and write have been provided with unique functionality.
However there is certain duplication in
write(int i)
print(int i)
print(String s)
write(String s)
But the print(int i) will call the write(int i) internally and the
print(String s) will call write(String s) internally.
Rahul P. Mahindrakar
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!