Java Type Casting

In Java, there are eight “primitive” data types – byte, short, char, int, long, float, double, and boolean.

Seven of these types are compatible enough that you can convert one type into another. This is a process called “type casting.” The type boolean, however, is not compatible, and therefore can’t be cast into another type. Neither can the other types be cast as a boolean.

Converting a smaller data type to a larger data type is called “widening casting.” It is done automatically when you assign a smaller type value to a larger type variable. Like so:

public class MyVariables {
  public static void main(String[] args) {
    byte myCoolVariable = 3;
    int aLessCoolVariable = myCoolVariable;
    System.out.println(aLessCoolVariable);
  }
}

Widening casting flows in this order –

byte➡short➡char➡int➡long➡float➡double

Keep in mind, though, that a float uses less memory than a long. So while the conversion from long to float may be automatic in Java, some data loss can occure.

Speaking of data loss, you are also allowed to cast from a larger data type to a smaller data type. This is called “narrowing casting.”

Narrowing casting flows in this order –

double➡float➡long➡int➡char➡short➡byte

Casting from a larger data type to a smaller one is not automatic and if you simply try you will get an error.

You might remember from Tutorial 4 that a value of type double can’t be assigned to a variable of type float. This is still true, but you can manually force a type cast from double to float like this:

public class MyVariables {
  public static void main(String[] args) {
    double myCoolVariable = 9.87654321;
    float aLessCoolVariable = (float)myCoolVariable;
    System.out.println(aLessCoolVariable);
  }
}

Did you notice the loss of data? My output was “9.876543”.

Narrowing casting must always be done manually. Why? Because there is often a data loss when doing a narrowing cast. Java just wants to make sure you are certain about what you are doing.

Practice:

Create a bunch of variables of varying types. Practice casting them to other types. Note which types of casts lose data and so forth.

Next Topic: Methods

Comments

Popular Posts