Classes/Objects  «Prev 


Java Numeric Cast

The Cast1 program

The Cast1 program shows how simple it is to cast one numeric type to another. The d, f, and l variables are assigned double, float, and long values. These values are cast to variables of the byte, short, and int types. The results displayed by the program are 101, 12, and 10001, as you would expect.

Cast1

public class Cast1 {

  public static void main(String[] args) {
    double d = 101.5;
    float  f = 12.34f;
    long   l = 10001;
    byte   b = (byte)d;
    short  s = (short)f;
    int    i = (int)l;
    System.out.println(b);
    System.out.println(s);
    System.out.println(i);
  }
}


char values are unsigned integer values, so if you try to assign a negative number to one, the code will not compile. Here is an example:
char c3 = -123;

But you can forcefully assign a negative number to a char by casting it to char, as follows:
char c3 = (char)-123;

System.out.println("c3 = " + c3);
In the previous code, note how the literal value –123 is prefixed by (char). This practice is called casting. Casting is the forceful conversion of one data type to another data type. You can cast only compatible data types. For example, you can cast a char to an int and vice versa. But you cannot cast an int to a boolean value or vice versa. When you cast a bigger value to a data type that has a smaller range, you tell the compiler that you know what you are doing, so the compiler proceeds by chopping off any extra bits that may not fit into the smaller variable. One should use casting with caution since it may not always give you the correct converted values.
Exam Tip: The exam will test your understanding of the possible values that can be assigned to a variable of type char, including whether an assignment will result in a compilation error. The exam will not test you on the value that is actually displayed after assigning arbitrary integer values to a char data type.