In my servlet I gave both out.print
and out.write
. but both prints in the browser.
What is the exact difference between these two and when to use out.print
and out.write
?
In my servlet I gave both out.print
and out.write
. but both prints in the browser.
What is the exact difference between these two and when to use out.print
and out.write
?
There are three major differences:
1) If you try to print a null value of a String with out.write() , It will throw NullPointerException while out.print() will simply print NULL as a string.
2) out.print() can print Boolean values but out.write() can not.
3) If you are using out.write(), you simply can not place arithmetic operation code but out.print() provides the support.
First thing is you can't use
javax.servlet.jsp.JspWriter out
in a servlet. It has to be used in a.jsp
file, becauseout
is a method local variable in_jspService(...)
method of your.jsp
file.However,
JspWriter.print()
is capable of taking many types of arguments thanWriter.write()
.JspWriter.print()
Writer.write()
The basic difference is that
out.write()
explodes if you pass it a null:write() method only writes characters to stream(or console) but does not print, while print() method writes and print it on stream (or console).
first statement writes character 97 i.e 'a' on console but does not print, while second statement prints 'a' which is written already on stream and 'j' which is passed in print() method.
PrintWriter
's implementation communicates the difference better than javadocPrintWriter:
print method has higher level of abstraction.
Hope this helps.