Typecasting with Arrays of Primitives

Contact Us or call 1-877-932-8228
Typecasting with Arrays of Primitives

Typecasting with Arrays of Primitives

It is not possible to typecast an array of one type of primitive to an array of another type of primitive. For example, the following will cause compiler errors if the comment marks are removed:

Code Sample:

// typecasts with arrays

public class ArrayTypecast {

  public static void main(String[] args) {

    int i = 5;
    double d;

    d = i;
    i = (int) d;

    int inums[] = { 1, 2, 3, 4, 5 };
    double[] dnums;

    // line below fails
    //dnums = inums;

    dnums = new double[] { 1.1, 2.2, 3.3, 4.4 };

    // line below fails
    //inums = (int[]) dnums;


Neither an implicit or explicit typecast can be performed. With a single int i, the copy of it that is given to d can be expanded to a double. But, with the int[] inums, the value that would be given to dnums is just a copy of the reference to inums, so there is no way that each of the individual elements can be expanded to double.

The next chapter will discuss typecasting from arrays of one type of object to another.