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
}
}
When dealing with primitive arrays, we can provide any type which can be implicity 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 declared type object or it's child type object as array elements:
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, implmentation class objects are allowed as array elements.
Array type | Allowed element type |
---|---|
primitive arrays | any type which can be implicity promoted to declared type |
Object type arrays | declared type or it's child class objects |
abstract class type array | it's child class object |
interface type array | it's implmentation class object |