Casting Incompatible Types : Data Type Conversion « Data Type « Java Tutorial






public class MainClass {
  public static void main(String args[]) {
    byte b;
    int i = 257;
    double d = 323.142;
   
    System.out.println("\nConversion of int to byte.");
    b = (byte) i;
    System.out.println("i and b " + i + " " + b);
   
    System.out.println("\nConversion of double to int.");
    i = (int) d;
    System.out.println("d and i " + d + " " + i);
   
    System.out.println("\nConversion of double to byte.");
    b = (byte) d;
    System.out.println("d and b " + d + " " + b);
  }
}
Conversion of int to byte.
i and b 257 1

Conversion of double to int.
d and i 323.142 323

Conversion of double to byte.
d and b 323.142 67








2.16.Data Type Conversion
2.16.1.The Widening Conversion
2.16.2.The Narrowing Conversion
2.16.3.Narrowing conversion with information loss
2.16.4.An automatic type conversion
2.16.5.Casting Incompatible Types
2.16.6.Pass a string to the Integer class constructor and call the intValue()
2.16.7.Use toString method of Integer class to conver Integer into String.
2.16.8.Declaring Checked Exceptions
2.16.9.Automatic Type Promotion in Expressions
2.16.10.Convert byte array to Integer and Long
2.16.11.Class with methods for type conversion
2.16.12.Data type conversion
2.16.13.Convert primitive back and forth