Array element assignment

Case 1: primitive type array

import java.lang.*;

class Test {
    public static void main(String[] args) {
        int[] x = new int[5];
        x[0] = 10;
        x[0] = 'a';
        byte b = 20;
        x[2] = b;
        short s = 30;
        x[3] = s;
        x[4] = 10l; // INVALID - compile-time error: posssible loss of precision, found long, required int
    }
}
Diagram showing that you can assign lower data type to higher data type variable.
Diagram showing that you can assign lower data type to higher data type variable.

When dealing with primitive arrays, we can provide any type which can be implicitly promoted to declared type

Case 2: object type array

import java.lang.*;

class Test {
    public static void main(String[] args) {
        Object[] a = new Object[10];
        a[0] = new Object();
        a[1] = new String("abc");
        a[2] = new Integer(10);
    }
}

In the case of object type arrays, we can provide the declared type object, or it's child type object as array elements:

Diagram illustrating number abstract class and it's implemented class types.
Diagram illustrating number abstract class and it's implemented class types.
import java.lang.*;

class Test {
    public static void main(String[] args) {
        Number[] n = new Number[10];
        n[0] = new Integer(10);
        n[1] = new Double(10.5);
        n[2] = new String("abc"); // INVALID: Compile time error: Incompatible types, found String, required Number
    }
}

Case 3: interface type array

import java.lang.*;

class Test {
    public static void main(String[] args) {
        Runnable[] r = new Runnable[10]; // VALID
        r[0] = new Thread(); // VALID: Thread implments Runnable
        r[1] = new String("abc"); // INVALID: Compile time error: Incompatible types, found j.l.String, required j.l.Runnable
    }
}

In the example above, Runnable is an interface, though you cannot create an instance of an interface, you can create an array of interface type. String does not implement Runnable, therefore it cannot be used as an array element in a Runnable array.

For interface type arrays, implementation class objects are allowed as array elements.

Array typeAllowed element type
primitive arrays any type which can be implicitly promoted to declared type
Object type arraysdeclared type or it's child class objects
abstract class type arrayit's child class object
interface type arrayit's implementation class object