Java Reference
In-Depth Information
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 add, as 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 basic types has an
equivalent class defined, so for the types we have discussed earlier there are the following classes:
Basic Type
Wrapper Class
byte
Byte
short
Short
int
Integer
long
Long
float
Float
double
Double
boolean
Boolean
character
Character
A value of one of the basic types is passed to the toString() method of the corresponding class as an
argument, and that returns the String equivalent. All of this happens automatically when you are
concatenating strings using the + operator. As we shall see, not only these classes have a toString()
method - all classes do. We won't go into the further significance of these classes now, as we'll be
covering these in more detail in Chapter 5.
The String class also defines a method, valueOf() , that will create a String object from a value of
any of the basic types. You just pass the value you want converted to a string as the argument to the
method, for instance:
Search WWH ::




Custom Search