Java Reference
In-Depth Information
Parentheses also can improve the readability of an expression. If the precedence of an
expression isn't immediately clear to you, adding parentheses to impose the desired
precedence can make the statement easier to understand.
String Arithmetic
As stated earlier today, the + operator has a double life outside the world of mathematics.
It can concatenate two or more strings. Concatenate means to link two things together.
For reasons unknown, it is the verb of choice when describing the act of combining two
strings—winning out over paste , glue , affix , combine , link , and conjoin .
2
In several examples, you have seen statements that look something like this:
String firstName = “Raymond”;
System.out.println(“Everybody loves “ + firstName);
These two lines result in the display of the following text:
Everybody loves Raymond
The + operator combines strings, other objects, and variables to form a single string. In
the preceding example, the literal “Everybody loves” is concatenated to the value of the
String object firstName .
Working with the concatenation operator is easy in Java because of the way the operator
can handle any variable type and object value as if it were a string. If any part of a con-
catenation operation is a String or a string literal, all elements of the operation will be
treated as if they were strings:
System.out.println(4 + “ score and “ + 7 + “ years ago”);
This produces the output text 4 score and 7 years ago , as if the integer literals 4 and
7 were strings.
There is also a shorthand += operator to add something to the end of a string. For exam-
ple, consider the following expression:
myName += “ Jr.”;
This expression is equivalent to the following:
myName = myName + “ Jr.”;
In this example, it changes the value of myName , which might be something like “Efrem
Zimbalist”, by adding “Jr.” at the end to form the string “Efrem Zimbalist Jr.”
 
Search WWH ::




Custom Search