Java Reference
In-Depth Information
1
// Fig. 2.6: Welcome4.java
2
// Displaying multiple lines with method System.out.printf.
3
4
public class
Welcome4
5
{
6
// main method begins execution of Java application
7
public static void
main(String[] args)
8
{
9
System.out.printf(
"%s%n%s%n"
,
"Welcome to"
,
"Java Programming!"
);
10
11
}
// end method main
12
}
// end class Welcome4
Welcome to
Java Programming!
Fig. 2.6
|
Displaying multiple lines with method
System.out.printf
.
Lines 9-10
System.out.printf(
"%s%n%s%n"
,
"Welcome to"
,
"Java Programming!"
);
call method
System.out.printf
to display the program's output. The method call speci-
fies three arguments. When a method requires multiple arguments, they're placed in a
comma-separated list
. Calling a method is also referred to as
invoking
a method.
Good Programming Practice 2.6
Place a space after each comma (
,
) in an argument list to make programs more readable.
Lines 9-10 represent only
one
statement. Java allows large statements to be split over
many lines. We indent line 10 to indicate that it's a
continuation
of line 9.
Common Programming Error 2.6
Splitting a statement in the middle of an identifier or a string is a syntax error.
Method
printf
's first argument is a
format string
that may consist of
fixed text
and
format specifiers
. Fixed text is output by
printf
just as it would be by
print
or
println
.
Each format specifier is a
placeholder
for a value and specifies the
type of data
to output.
Format specifiers also may include optional formatting information.
Format specifiers begin with a percent sign (
%
) followed by a character that represents
the
data type
. For example, the format specifier
%s
is a placeholder for a string. The format
string in line 9 specifies that
printf
should output two strings, each followed by a newline
character. At the first format specifier's position,
printf
substitutes the value of the first
argument after the format string. At each subsequent format specifier's position,
printf
substitutes the value of the next argument. So this example substitutes
"Welcome
to"
for
the first
%s
and
"Java
Programming!"
for the second
%s
. The output shows that two lines
of text are displayed on two lines.
Notice that instead of using the escape sequence
\n
, we used the
%n
format specifier,
which is a line separator that's
portable
across operating systems. You cannot use
%n
in the