Page 1 of 1

About Question enthuware.ocpjp.v8.2.1907 :

Posted: Tue Jun 14, 2016 11:49 am
by RoyEL1
I find it a bit curious w.r.t.

Code: Select all

public void outputText(PrintWriter pw, String text) {
         pw.printf(text).print("success"); 
}
that the execution works, but the Java Platform Standard Ed. 8 (JDK SE8) Documentation states that for a PrintWriter, the printf(String format, Objects ... arg) and the printf(Locale l, String format, Objects ... arg) both state that it will throw a NullPointerException if the format string is null.

Is it the case that with only 1 string passed in, the JVM considers the string already formatted?

Re: About Question enthuware.ocpjp.v8.2.1907 :

Posted: Tue Jun 14, 2016 8:26 pm
by admin
Acutally, the first argument to printf is the format string. So here, it is not the format string that is null but the arg parameter that is null. So there is no reason for it to throw NPE.
It will not write anything to the stream though (because there is no argument to write).

It would be better if changed to pw.printf("%s", text)

HTH,
Paul.