Java Reference
In-Depth Information
5.1.8 ) ), or a ClassCastException (as a result of an unchecked conversion (§ 5.1.9 )) to
be thrown at run time.
• Casting conversion (§ 5.5 ) converts the type of an expression to a type explicitly
specified by a cast operator (§ 15.16 ) .
It is more inclusive than assignment or method invocation conversion, allowing
any specific conversion other than a string conversion, but certain casts to a refer-
ence type may cause an exception at run time.
• String conversion (§ 5.4 ) applies only to an operand of the binary + operator which
is not a String when the other operand is a String .
String conversion may cause an OutOfMemoryError (as a result of class instance cre-
ation (§ 12.5 ) ) to be thrown at run time.
• Numeric promotion (§ 5.6 ) brings the operands of a numeric operator to a common
type so that an operation can be performed.
Example 5.0-2. Conversion Contexts
Click here to view code image
class Test {
public static void main(String[] args) {
// Casting conversion (5.4) of a float literal to
// type int. Without the cast operator, this would
// be a compile-time error, because this is a
// narrowing conversion (5.1.3):
int i = (int)12.5f;
// String conversion (5.4) of i's int value:
System.out.println("(int)12.5f==" + i);
// Assignment conversion (5.2) of i's value to type
// float. This is a widening conversion (5.1.2):
float f = i;
// String conversion of f's float value:
System.out.println("after float widening: " + f);
// Numeric promotion (5.6) of i's value to type
// float. This is a binary numeric promotion.
// After promotion, the operation is float*float:
System.out.print(f);
f = f * i;
// Two string conversions of i and f:
System.out.println("*" + i + "==" + f);
// Method invocation conversion (5.3) of f's value
// to type double, needed because the method Math.sin
// accepts only a double argument:
Search WWH ::




Custom Search