views:

78

answers:

3

My question is about line (edit: 19), where the new PrintWriter is created with the constructor taking the FileWriter fw as a parameter. I don't understand the use of chaining the BufferedWriter bw to FileWriter if it isn't used later on in the actual writing. Can Java apply chaining in a way that bw still somehow affects the rest of the program?

16.         try {
17.             FileWriter fw = new FileWriter(test);
18.             BufferedWriter bw = new BufferedWriter(fw, 1024);
19.             PrintWriter out = new PrintWriter(fw);
20.             out.println("<html><body><h1>");
21.             out.println(args[0]);
22.             out.println("</h1></body></html>");
23.             out.close();
24.             bw.close();
25.             fw.close();
26.         }catch(IOException e) {
27.             e.printStackTrace();
28.         }

I think it is probably a typo and they meant to use bw as the parameter for PrintWriter out but like the title says, I'm new to this.

Thanks to all in advance.

+3  A: 

You are correct, this looks like a typo.

Line 18 should have no affect on the outcome of running this code.

The BufferedWriter Javadoc shows a normal example of how FileWriter, BufferedWriter and PrintWriter are typically used.

derivation
+1  A: 

Which exact book is this? There are a few--the first place to look would be to go to the publisher's page for the book and look for the errata section. Chances are good that this is an error because, no, Java isn't chaining these particular objects (chaining wouldn't really be the right word, that would be more of a side effect). If you do find the errata page and it's not listed, you could always submit it to the authors via the site, and let them decide.

Marc Bollinger
This is SCJP: "Sun Certified Programmer for Java Platform, Standard Edition 6 Study Guide (CX-310-065)" by Richard F. Raposa
Looks like the errata page is: http://www.sybex.com/WileyCDA/SybexTitle/SCJP-Sun-Certified-Programmer-for-Java-Platform-Study-Guide-SE6-Exam-CX-310-065-.productCd-0470417978,navId-290636,pageCd-errata.html There currently isn't a listing for this typo, but the fact that there's only one listed leads me to believe the list may not exactly be indicative of the actual number (the McGraw-Hill book has pages of errata; that to me speaks not of lack of quality, but of transparency).
Marc Bollinger
A: 

It compiles and produces the same result either way, but yeah, it looks like a typo.

Michael Angstadt