Primitive Type Casting « Type Casting « SCJP
Java Source And Data Type
Primitive Type Casting
4.2.Primitive Type Casting
Widening and Narrow conversions
Implicit and explicit casting
Primitive Conversion: Assignment
Primitives widening rules during evaluating an arithmetic expression with two operands
The String + operator results in the concatenation of two String objects.
When one of the operands in a + operation is a String, then the other operand is converted to a String.
Casting and the += Operator
If the other operand is an object, then its toString() method is invoked to convert it to a String object.
Incompatible type Conversion
A boolean cannot be converted to any other type.
Java relaxes its assignment conversion rule
Relaxation of assignment applies only when the assigned value is an integral literal.
Primitive Conversion: Method Call
Incompatible type for method. Explicit cast needed to convert double to int for parameter passing
For unary operators, if the operand is a byte, a short, or a char, it is converted
Casting is explicitly telling Java to make a conversion.
Casts are required when you want to perform a narrowing conversion.
Cast any non-boolean type to any other non-boolean type.
You cannot cast a boolean to any other type; you cannot cast any other type to a boolean.
Conversion with Casting
You cannot simply convert a char to a short with code
Example of the method signature controlling conversion of primitives
A double value too small to be represented as a float becomes a positive or negative zero.
A double with the special NaN value becomes the float NaN value.
To assign a double value to an integer type
Cast the floating-point number into an int
Cast a floating-point number to an integer type. The value loses all the digits after the decimal.
Cast a larger number type, such as a long, into a smaller number type, such as a byte.
What happens if the long value is larger than 127 when casting long to byte
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.