Java Reference
In-Depth Information
You saw in Chapter 1 that you can output string literals using
System.out.println
.
You can also output numeric expressions using
System.out.println
:
System.out.println(12 + 3 - 1);
This statement causes the computer first to evaluate the expression, which yields
the value
14
, and then to write that value to the console window. You'll often want to
output more than one value on a line, but unfortunately, you can pass only one value
to
println
. To get around this limitation, Java provides a simple mechanism called
concatenation
for putting together several pieces into one long string literal.
String Concatenation
Combining several strings into a single string, or combining a string with
other data into a new, longer string.
The addition (
+
) operator concatenates the pieces together. Doing so forms an
expression that can be evaluated. Even if the expression includes both numbers and
text, it can be evaluated just like the numeric expressions we have been exploring.
Consider, for example, the following:
"I have " + 3 + " things to concatenate"
You have to pay close attention to the quotation marks in an expression like this to
keep track of which parts are “inside” a string literal and which are outside. This
expression begins with the text
"
I have
"
(including a space at the end), followed
by a plus sign and the integer literal
3
. Java converts the integer into a textual form
(
"
3
"
)
and concatenates the two pieces together to form
"
I have 3
"
. Following the
3
is another plus and another string literal,
"
things to concatenate
"
(which
starts with a space). This piece is glued onto the end of the previous string to form the
string
"
I have 3 things to concatenate
"
.
Because this expression produces a single concatenated string, we can include it in
a
println
statement:
System.out.println("I have " + 3 + " things to concatenate");
This statement produces a single line of output:
I have 3 things to concatenate
String concatenation is often used to report the value of a variable. Consider, for
example, the following program that computes the number of hours, minutes, and
seconds in a standard year:
1
public class
Time {
2
public static void
main(String[] args) {
3
int
hours = 365 * 24;
Search WWH ::
Custom Search