Java Reference
In-Depth Information
theactualcarriagereturncode(13),whichissymbolicallyrepresentedby
\r
,followed
bytheactualnewline/linefeedcode(10),whichissymbolicallyrepresentedby
\n
.In
contrast,
System.getProperty("line.separator")
returns only the actual
newline/line feed code on Unix and Linux platforms.
The
println()
methods call their corresponding
print()
methods followed
by the equivalent of the
void println()
method, which eventually results in
line.separator
's value being output. For example,
void println(int x)
outputs
x
's string representation and calls this method to output the line separator.
Caution
Neverhard-codethe
\n
escapesequenceinaliteralstringthatyouarego-
ingtooutputviaa
print()
or
println()
method.Doingsoisn'tportable.Forex-
ample,whenJavaexecutes
System.out.print("first line\n");
followed
by
System.out.println("second line");
, you'll see
first line
on
onelinefollowedby
second line
onasubsequentlinewhenthisoutputisviewed
attheWindowscommandline.Incontrast,you'llsee
first linesecond line
whenthisoutputisviewedintheWindowsNotepadapplication(whichrequiresacar-
riage return/line feed sequence to terminate lines). When you need to output a blank
line,theeasiestwaytodothisistocall
System.out.println();
,whichiswhy
youfindthismethodcallscattered throughoutmybook.IconfessthatIdon'talways
followmyownadvice,soyoumightfindinstancesof
\n
inliteralstringsbeingpassed
to
System.out.print()
or
System.out.println()
elsewhere in this topic.
PrintStream
offers two other features that you'll find useful:
• Unlikeotheroutputstreams,aprintstreamneverrethrowsan
IOException
instance thrown from the underlying output stream. Instead, exceptional situ-
ations set an internal flag that can be tested by calling
PrintStream
's
boolean checkError()
method,whichreturnstruetoindicateaproblem.
•
PrintStream
objects can be created to automatically flush their output to
theunderlyingoutputstream.Inotherwords,the
flush()
methodisautomat-
ically called after a byte array is written, one of the
println()
methods is
called,oranewlineiswritten.The
PrintStream
instancesassignedto
Sys-
tem.out
and
System.err
automaticallyflushtheiroutputtotheunderlying
output stream.