type, dropping the upper bits changes the value, including possibly changing sign. The code
short s = -134;
byte b = (byte) s;
System.out.println("s = " + s + ", b = " + b);
produces the following output because the upper bits of s are lost when the value is stored in b:
s = -134, b = 122
A char can be cast to any integer type and vice versa. When an integer is cast to a char, only the bottom 16
bits of data are used; the rest are discarded. When a char is cast to an integer type, any additional upper bits
are filled with zeros.
Once those bits are assigned, they are treated as they would be in any other value. Here is some code that casts
a large Unicode character to both an int (implicitly) and a short (explicitly). The int is a positive value
equal to 0x0000ffff, because the upper bits of the character were set to zero. But the same bits in the
short are a negative value, because the top bit of the short is the sign bit:
class CharCast {
public static void main(String[] args) {
int i = '\uffff';
short s = (short) '\uffff';
System.out.println("i = " + i);
System.out.println("s = " + s);
}
}
And here is the program's output:
i = 65535
s = -1
9.4.3. String Conversions
One special type of implicit conversion involves both the primitive and reference types: string conversion.
Whenever a + operator has at least one String operand, it is interpreted as the string concatenation operator
and the other operand, if not a String, is implicitly converted into a String. Such conversions are
predefined for all primitive types. Objects are converted via the toString method, which is either inherited
from Object or overridden to provide a meaningful string representation. For example, the following
method brackets a string with the guillemet characters used for quotation marks in many European languages:
public static String guillemete(String quote) {
return '«' + quote + '»';
}