Java Reference
In-Depth Information
The next addition involves adding the integer 5 to the string literal " hello " . If
either of the two operands is a string, we perform concatenation. So, in this case, we
convert the integer into a text equivalent ("5") and glue the pieces together to form a
new string value:
5 + " hello " + 7 + 6
"5 hello " + 7 + 6
You might think that Java would add together the 7 and 6 the same way it added the 2
and 3 to make 5 . But it doesn't work that way. The rules of precedence are simple, and
Java follows them with simple-minded consistency. Precedence tells us that addition
operators are evaluated from left to right, so first we add the string "5 hello " to 7 .
That is another combination of a string and an integer, so Java converts the integer to its
textual equivalent ("7") and concatenates the two parts together to form a new string:
"5 hello " + 7 + 6
"5 hello 7"
+ 6
Now there is just a single remaining addition to perform, which again involves a
string/integer combination. We convert the integer to its textual equivalent ( " 6 " ) and
concatenate the two parts together to form a new string:
"5 hello 7" + 6
"5 hello 76"
Clearly, such expressions can be confusing, but you wouldn't want the Java compiler
to have to try to guess what you mean. Our job as programmers is easier if we know
that the compiler is going to follow simple rules consistently. You can make the expres-
sion clearer, and specify how it is evaluated, by adding parentheses. For example, if we
really did want Java to add together the 7 and 6 instead of concatenating them sepa-
rately, we could have written the original expression in the following much clearer way:
(2 + 3) + " hello " + (7 + 2 * 3)
Because of the parentheses, Java will evaluate the two numeric parts of this
expression first and then concatenate the results with the string in the middle. This
expression evaluates to " 5 hello 13 " .
Increment/Decrement Operators
In addition to the standard assignment operator, Java has several special operators
that are useful for a particular family of operations that are common in programming.
As we mentioned earlier, you will often find yourself increasing the value of a vari-
able by a particular amount, an operation called incrementing . You will also often
 
Search WWH ::




Custom Search