Writer and PrintWriter

Y

yzzzzz

Hi,

What is the difference between PrintWriter.write(String) and
PrintWriter.print(String)?

And how can PrintWriter.write not throw IOException when Writer.write
does? Should the overriding method have the same signature?

Thanks.
 
R

Roland

Hi,

What is the difference between PrintWriter.write(String) and
PrintWriter.print(String)?

PrintWriter.print(String) prints the literal string "null" if the
argument is null. Otherwise it's the same as PrintWriter.write(String)
Source from 1.4.2
public void print(String s) {
if (s == null) {
s = "null";
}
write(s);
}

And how can PrintWriter.write not throw IOException when Writer.write
does? Should the overriding method have the same signature?

Thanks.

The signature of a method does not include the thrown exceptions, only
its name, and the number and types of its parameters. See JLS §8.4.2
<http://java.sun.com/docs/books/jls/second_edition/html/classes.doc.html#38649>

And from JLS §8.4.4
<http://java.sun.com/docs/books/jls/second_edition/html/classes.doc.html#78323>:
"A method that overrides or hides another method [...] may not be
declared to throw more checked exceptions than the overridden or hidden
method."
In other words, a method overriding a method of a parent class may be
declared with fewer checked exceptions.
--
Regards,

Roland de Ruiter
___ ___
/__/ w_/ /__/
/ \ /_/ / \
 
Y

yzzzzz

Roland said:
PrintWriter.print(String) prints the literal string "null" if the
argument is null. Otherwise it's the same as PrintWriter.write(String)
Source from 1.4.2
public void print(String s) {
if (s == null) {
s = "null";
}
write(s);
}

Hm. Weird!

And how can PrintWriter.write not throw IOException when Writer.write
does? Should the overriding method have the same signature?

Thanks.

The signature of a method does not include the thrown exceptions, only
its name, and the number and types of its parameters. See JLS §8.4.2
<http://java.sun.com/docs/books/jls/second_edition/html/classes.doc.html#38649>

And from JLS §8.4.4
<http://java.sun.com/docs/books/jls/second_edition/html/classes.doc.html#78323>:

"A method that overrides or hides another method [...] may not be
declared to throw more checked exceptions than the overridden or hidden
method."
In other words, a method overriding a method of a parent class may be
declared with fewer checked exceptions.

Ok. That does make sense.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top