Casting Primitives : Primitive Type Casting « Type Casting « SCJP






public class MainClass {
  public static void main(String[] argv) {
    double d = Math.sqrt(-1.0); // i.e. Double.NaN
    int x = (int) d;
    System.out.println("Value = " + x);

    System.out.println();
  }
}
Value = 0








4.2.Primitive Type Casting
4.2.1.Widening and Narrow conversions
4.2.2.Implicit and explicit casting
4.2.3.Primitive Conversion: Assignment
4.2.4.Primitives widening rules during evaluating an arithmetic expression with two operands
4.2.5.The String + operator results in the concatenation of two String objects.
4.2.6.When one of the operands in a + operation is a String, then the other operand is converted to a String.
4.2.7.Casting and the += Operator
4.2.8.If the other operand is an object, then its toString() method is invoked to convert it to a String object.
4.2.9.Incompatible type Conversion
4.2.10.A boolean cannot be converted to any other type.
4.2.11.Java relaxes its assignment conversion rule
4.2.12.Relaxation of assignment applies only when the assigned value is an integral literal.
4.2.13.Primitive Conversion: Method Call
4.2.14.Incompatible type for method. Explicit cast needed to convert double to int for parameter passing
4.2.15.For unary operators, if the operand is a byte, a short, or a char, it is converted
4.2.16.Casting is explicitly telling Java to make a conversion.
4.2.17.Casts are required when you want to perform a narrowing conversion.
4.2.18.Cast any non-boolean type to any other non-boolean type.
4.2.19.You cannot cast a boolean to any other type; you cannot cast any other type to a boolean.
4.2.20.Conversion with Casting
4.2.21.You cannot simply convert a char to a short with code
4.2.22.Example of the method signature controlling conversion of primitives
4.2.23.Casting Primitives
4.2.24.A double value too small to be represented as a float becomes a positive or negative zero.
4.2.25.A double with the special NaN value becomes the float NaN value.
4.2.26.To assign a double value to an integer type
4.2.27.Cast the floating-point number into an int
4.2.28.Cast a floating-point number to an integer type. The value loses all the digits after the decimal.
4.2.29.Cast a larger number type, such as a long, into a smaller number type, such as a byte.
4.2.30.What happens if the long value is larger than 127 when casting long to byte