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
First thing is you can't use javax.servlet.jsp.JspWriter out
in a servlet. It has to be used in a .jsp
file, because out
is a method local variable in _jspService(...)
method of your .jsp
file.
There is no difference in the purpose of using
out.print()
andout.write()
. Both are used to write theString
version of the given object to JspWriter's buffer.
However, JspWriter.print()
is capable of taking many types of arguments than Writer.write()
.
JspWriter.print()
Writer.write()
PrintWriter
's implementation communicates the difference better than javadoc
public void print(String s) {
if (s == null) {
s = "null";
}
write(s);
}
PrintWriter:
public void write(String s)
Write a string. This method cannot be inherited from the Writer class because it must suppress I/O exceptions.
print method has higher level of abstraction.
public void print(String s)
Print a string. If the argument is null then the string "null" is printed. Otherwise, the string's characters are converted into bytes according to the platform's default character encoding, and these bytes are written in exactly the manner of the write(int) method.
Hope this helps.