Page 484 - Introduction to Programming with Java: A Problem Solving Approach
P. 484

                450 Chapter 11 Type Details and Alternate Coding Mechanisms
Expression Evaluation Practice with Characters and String Concatenation
Note the following three expressions. Try to evaluate them on your own prior to looking at the subsequent an- swers. While performing the evaluations, remember that if you have two or more operators with the same pre- cedence, use left-to-right associativity (i.e., perform the operation at the left first). So in the first expression, youshouldperformthe􏰁operationin'1' + '2'beforeattemptingtoperformthesecond+operation.
1. '1' + '2' + "3" + '4' + '5' 2. 1 + 2 + "3" + 4 + 5
3.1 + '2'
Here are the answers:
1.
'1' + '2' + "3" + '4' + '5' ⇒ 49 + 50 + "3" + '4' + '5' ⇒ 99 + "3" + '4' + '5' ⇒
"993" + '4' + '5' ⇒
  When adding two chars, use their underlying ASCII numeric values.
                      "9934" + '5' ⇒ "99345"
2.
Apago PDF Enhancer
     1 + 2 + "3" + 4 + 5 ⇒ 3 + "3" + 4 + 5 ⇒
"33" + 4 + 5 ⇒
"334" + 5 ⇒
"3345"
3.
1 + '2' ⇒ 1 + 50 ⇒ 51
Expression Evaluation Practice with Type Conversions and Various Operators
Assume:
int a = 5, b = 2;
                double c = 3.0;
When the JVM sees a string next
to a + sign, it concatenates by first converting the operand on the other side of the + sign to a string.
Left-to-right associativity dictates adding the two numbers at the left.
 Mixed expression—the char gets promoted to an int, using the underlying ASCII numeric value for ‘2.’








































































   482   483   484   485   486