(^62) | Java Syntax and Semantics, Classes, and Objects
then bookTitleis set equal to the string
“with JavaIntroduction to Programming and Problem Solving ”
Concatenation works with named Stringconstants and literal strings as well as String
variables. For example, suppose we have declared the following constants:
finalString WORD1 = “Introduction”;
finalString WORD3 =“Programming”;
finalString WORD5 = “with Java”;
Then we could write the following statement to assign the title of this book to the variable
bookTitle:
bookTitle = WORD1 + “ to “+ WORD3 + “ and Problem Solving “+ WORD5;
As a result,bookTitleis assigned the following string:
“Introduction to Programming and Problem Solving with Java”
The preceding example demonstrates how we can combine identifiers and literal strings
in a concatenation expression. Of course, if we simply want to assign the complete string to
bookTitle, we can do so directly:
bookTitle = “Introduction to Programming and Problem Solving with Java”;
Occasionally, however, we need to assign a string literal that is too long to fit on one
line. Then a concatenation expression is necessary, as in the following statement:
longSentence = “The Red-Wing Blackbird hovered precariously in the gusty “+
“breeze as he tried to display his brilliant red and “+
“yellow epaulets to his rival suitor. “;
Sometimes we may encounter a situation in which we want to add some characters to
an existing string value. Suppose that bookTitlealready contains ”Introduction to Programming”
and that we wish to complete the title. We could use a statement of the form
bookTitle = bookTitle + “ and Problem Solving with Java”;
This statement retrieves the value of bookTitlefrom memory, concatenates the string “ and
Problem Solving with Java”to form a new string, and then assigns the new string back to
bookTitle. The new string replaces the old value of bookTitle(which is destroyed).
Concatenation works only with values of the class String. If we try to concatenate a
value of one of Java’s built-in types with a string, Java will automatically convert the value
into an equivalent string and perform the concatenation. For example, the code segment
String result;
result = “The square of 12 is “+ 144;
やまだぃちぅ
(やまだぃちぅ)
#1