Java Array assignment

In this tutorial on Java Arrays, we will see to how to assign an array – both Primitive Array assignment and Reference Array assignment.

Java Primitive Array Assignment

If an array is declared as int (int[]) then you can assign another int array of any size but cannot assign anything that is not an int array including primitive int variable. Following is an example of int[] array assignment.

package com.ibytecode.arrays;
public class PrimitiveArrayAssignments {
	public static void main(String[] args) {
		int i = 10;
		int[] numbers;
		int[] marks = {80,90,70,60};
		char[] letters = new char[4];
		
		numbers = marks;
		//numbers = letters; //No.ERROR
		//numbers = i; //No. ERROR
	}
}

Java Reference Array Assignment

If an array is declared as a reference type then you can assign any other array reference which is a subtype of the declared reference type, i.e.) it should pass the “IS-A relationship”. Following is an example of reference array assignment.

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

public class ReferenceArrayAssignment {
	public static void main(String[] args) {
		Animal[] animals;
		
		Cat[] cats = new Cat[5];
		Dog[] puppies = new Dog[5];
		Person[] persons;
		
		animals = cats; //OK. Cat IS-A Animal
		animals = puppies; //OK. Dog IS-A Animal
		//animals = persons; // No. ERROR. Person IS NOT A Animal
	}
}

Similarly, if an array is declared as interface type then it can reference an array of any type that 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 ReferenceArrayAssignment {
	public static void main(String[] args) {
		LivingBeing[] lives = new LivingBeing[5];
		Animal[] animals = new Animal[4];
		Person[] persons = new Person[5];
		Plant[] plants = new Plant[3];
		Vehicle[] vehicles;
		
		lives = animals; //OK. Animal IS-A LivingBeing
		lives = persons;//OK. Person IS-A LivingBeing
		lives = plants;//OK. Plant IS-A LivingBeing
		//lives = vehicles; //NO. ERROR. Vehicle IS NOT A LivingBeing
	}
}

Leave a Comment

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