, ,

Other Conversions – Basic Elements, Primitive Data Types, and Operators

Other Conversions

Here we briefly mention some other conversions.

  • Identity conversions allow conversions from a type to that same type. An identity conversion is always permitted.

Click here to view code image

int i = (int) 10;                   // int <—- int
String str = (String) “Hi”;         // String <—- String

  • String conversions allow a value of any other type to be converted to a String type in the context of the string concatenation operator + (p. 67).
  • Unchecked conversions are permitted to facilitate operability between legacy and generic code (§11.2, p. 575).

2.4 Type Conversion Contexts

Selected conversion contexts and the conversions that are applicable in these contexts are summarized in Table 2.17. The conversions shown in each context occur implicitly, without the program having to take any special action. For other conversion contexts, see §2.3, p. 46.

Table 2.17 Selected Conversion Contexts and Conversion Categories

Assignment Context

Assignment conversions that can occur in an assignment context are shown in the second column of Table 2.17. An assignment conversion converts the type of an expression to the type of a target variable.

An expression (or its value) is assignable to the target variable, if the type of the expression can be converted to the type of the target variable by an assignment conversion. Equivalently, the type of the expression is assignment compatible with the type of the target variable.

For assignment conversion involving primitive data types, see §2.7, p. 54. Note the special case where a narrowing conversion occurs when assigning a non-long integer constant expression:

Click here to view code image

byte b = 10;   // Narrowing conversion: byte <— int

For assignment conversions involving reference types, see §5.8, p. 261.

Related Posts