Java Array Elements

Array elements in Java can have only one declared type (int[], char[], Person[], Animal[]) and it need not necessarily mean that it can hold elements only of that type.

Java Primitive array elements

If an array is declared as any primitive type, it can hold any elements which can be implicitly promoted to that declared type.
Example of a Java primitive array elements,

package com.ibytecode.arrays;
public class PrimitiveArrayElements {
	public static void main(String[] args) {
		int[] numbers = new int[4];
		byte b = 10;
		short s = 20;
		char c = 'r';
		long l = 100;
		numbers[0] = b;
		numbers[1] = s;
		numbers[2] = c;
		//numbers[3] = l; //ERROR. long cannot be implicitly promoted to int
	}
}

Another example where ‘double’ array can hold any element which can be implicitly promoted to double.

package com.ibytecode.arrays;
public class PrimitiveArrayElements {
	public static void main(String[] args) {
		byte b = 10;
		short s = 20;
		char c = 'r';
		long l = 100;
		int i = 400;
		double d = 12.6;
		double[] array = new double[7];
		array[0] = d;
		array[1] = 10.0f;
		array[2] = l;
		array[3] = i;
		array[4] = s;
		array[5] = b;
		array[6] = c;
	}
}

Java Reference array elements

If an array is declared as reference type then it can hold any element which is a subclass of the declared type, i.e.) elements should satisfy ‘IS-A relationship’.
Example of a java reference array elements.

package com.ibytecode.arrays;

class Animal { }
class Cat extends Animal { }
class Dog extends Animal { }

public class ReferenceArrayElements {
	public static void main(String[] args) {
		//Cat IS-A Animal and Dog IS-A Animal
		Animal[] animals = {new Animal(), new Cat(), new Dog()};
		//animals[0] = new Object(); // ERROR
	}
}

If an array is declared as interface type then it can hold any object which implements that interface.

package com.ibytecode.arrays;

interface LivingBeing {}
class Animal implements LivingBeing {}
class Person implements LivingBeing {}
class Plant implements LivingBeing {}
class Vehicle {}
public class ArrayInterfaceType {
	public static void main(String[] args) {
		LivingBeing[] lives = new LivingBeing[4];
		lives[0] = new Animal();
		lives[1] = new Person();
		lives[2] = new Plant();
		//lives[3] = new Vehicle(); //ERROR. Vehicle IS NOT A LivingBeing
	}
}

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.