Java Reference
In-Depth Information
A string literal cannot span multiple lines in a program. The following program
statement is improper syntax and would produce an error when attempting to
compile:
// The following statement will not compile
System.out.println ("The only stupid question is
the one that is not asked.");
When we want to print a string that is too long to fit on one line in a program,
we can rely on
string concatenation
to append one string to the end of another.
The string concatenation operator is the plus sign (+). The following expression
concatenates one character string to another, producing one long string:
"The only stupid question is " + "the one that is not asked."
The program called
Facts
shown in Listing 2.2 contains several
println
statements. The first one prints a sentence that is somewhat long and will not
fit on one line of the program. Since a character literal cannot span two lines in
a program, we split the string into two and use string concatenation to append
them. Therefore, the string concatenation operation in the first
println
statement
results in one large string that is passed to the method to be printed.
Note that we don't have to pass any information to the
println
method, as
shown in the second line of the
Facts
program. This call does not print any vis-
ible characters, but it does move to the next line of output. So in this case calling
println
with no parameters has the effect of printing a blank line.
The last three calls to
println
in the
Facts
program demonstrate another
interesting thing about string concatenation: Strings can be concatenated with
numbers. Note that the numbers in those lines are not enclosed in double quotes
and are therefore not character strings. In these cases, the number is automatically
converted to a string, and then the two strings are concatenated.
Because we are printing particular values, we simply could have included the
numeric value as part of the string literal, such as:
"Speed of ketchup: 40 km per year"
Digits are characters and can be included in strings as needed. We separate them
in the
Facts
program to demonstrate the ability to concatenate a string and a
number. This technique will be useful in upcoming examples.
As you can imagine, the
+
operator is also used for arithmetic addition.
Therefore, what the
+
operator does depends on the types of data on which it
Search WWH ::
Custom Search