Java Reference
In-Depth Information
1
// Fig. 2.3: Welcome2.java
2
// Printing a line of text with multiple statements.
3
4
public class
Welcome2
5
{
6
// main method begins execution of Java application
7
public static void
main(String[] args)
8
{
9
System.out.print(
"Welcome to "
);
System.out.println(
"Java Programming!"
);
10
11
}
// end method main
12
}
// end class Welcome2
Welcome to Java Programming!
Fig. 2.3
|
Printing a line of text with multiple statements.
is an end-of-line comment stating the purpose of the program. Line 4 begins the
Welcome2
class declaration. Lines 9-10 of method
main
System.out.print(
"Welcome to "
);
System.out.println(
"Java Programming!"
);
display one line of text. The first statement uses
System.out
's method
print
to display a
string. Each
print
or
println
statement resumes displaying characters from where the last
print
or
println
statement stopped displaying characters. Unlike
println
, after display-
ing its argument,
print
does
not
position the output cursor at the beginning of the next
line in the command window—the next character the program displays will appear
imme-
diately after
the last character that
print
displays. So, line 10 positions the first character
in its argument (the letter “
J
”) immediately after the last character that line 9 displays (the
space character
before the string's closing double-quote character).
Displaying Multiple Lines of Text with a Single Statement
A single statement can display multiple lines by using
newline characters
, which indicate
to
System.out
's
print
and
println
methods when to position the output cursor at the
beginning of the next line in the command window. Like blank lines, space characters and
tab characters, newline characters are whitespace characters. The program in Fig. 2.4 out-
puts four lines of text, using newline characters to determine when to begin each new line.
Most of the program is identical to those in Figs. 2.1 and 2.3.
1
// Fig. 2.4: Welcome3.java
2
// Printing multiple lines of text with a single statement.
3
4
public class
Welcome3
5
{
6
// main method begins execution of Java application
7
public static void
main(String[] args)
8
{
Fig. 2.4
|
Printing multiple lines of text with a single statement. (Part 1 of 2.)