Java Reference
In-Depth Information
When you use
System.out.println
for output, the data to be output is given
as an argument in parentheses, and the statement ends with a semicolon. Things you
can output are strings of text in double quotes, such as
"The changed string is:"
;
String
variables such as
sentence
; variables of other types such as variables of type
int
; numbers such as
5
or
7.3
; and almost any other object or value. If you want to
output more than one thing, simply place an addition sign between the things you
want to output. For example,
System.out.println("Answer is = " + 42
+ " Accuracy is = " + precision);
If the value of
precision
is
0.01
, the output will be
Answer is = 42 Accuracy is = 0.01
Notice the space at the start of
" Accuracy is = "
. No space is added automatically.
The
+
operator used here is the concatenation operator that we discussed earlier. So
the above output statement converts the number
42
to the string
"42"
and then forms
the following string using concatenation:
"Answer is = 42 Accuracy is = 0.01"
System.out.println
then outputs this longer string.
Every invocation of
println
ends a line of output. For example, consider the
following statements:
System.out.println("A wet bird");
System.out.println("never flies at night.");
These two statements cause the following output to appear on the screen:
A wet bird
never flies at night.
If you want the output from two or more output statements to place all their
output on a single line, then use
print
instead of
println
. For example, consider the
following statements:
print
versus
println
System.out.print("A ");
System.out.print("wet ");
System.out.println("bird");
System.out.println("never flies at night.");