Java Reference
In-Depth Information
Behind the scenes, the value of the variable numHands is being converted to a string that represents this
value as a decimal digit character. This is prompted by the fact that it is combined with the string literal,
" " , using the + operator. Dissimilar types in a binary operation cannot be operated on, so one operand
must be converted to the type of the other if the operation is to be possible. Here the compiler arranges
that the numerical value stored in numHands is converted to type String to match the type of the right
operand of the + operator. If you look back at the table of operator precedence, you'll see that the associ-
ativity of the + operator is from left to right, so the strings are combined in pairs starting from the left, as
shown in Figure 4-8 .
The left-to-right associativity of the + operator is important in understanding how the next two lines of
output are generated. The two statements involved in creating these strings look very similar. Why does
5 + 5 result in 55 in one statement and 10 in the other? The reason is illustrated in Figure 4-9 .
FIGURE 4-9
The essential difference between the two is that the first statement always has at least one operand of
type String , so the operation is one of string concatenation, whereas in the second statement the first
operation is an arithmetic addition because both operands are integers. In the first statement, each of the
integers is converted to type String individually. In the second, the numerical values are added, and the
result, 10 , is converted to a string representation to allow the literal "is ten" to be concatenated.
You don't need to know about this at this point, but in case you were wondering, the conversion of values
of the basic types to type String is actually accomplished by using a static method, toString() , of
a standard class that corresponds to the basic type. Each of the primitive types has an equivalent class
defined, so for the primitive types I have already discussed there are the wrapper classes shown in Table
4-1 .
TABLE 4-1 : Wrapper Classes
BASIC TYPE WRAPPER CLASS
byte
Byte
short
Short
int
Integer
long
Long
float
Float
double
Double
 
 
 
 
Search WWH ::




Custom Search