Array Creation

There are three ways of creating an array.

double[] studentAvgs = new double[5];
Person[] persons = {p1, p2, new Person("John"), new Person("Sri")};
Person[] arr = new Person[] {p1, p2};

Array Length

Length/size of the array can be obtained using

arrayReferenceName.length

Illegal Array Declaration

You should not specify the size when you declare the array

int[10] numbers;  //Compiler error
int numbers[10];  //Compiler error 

Array instance/static field

Instance or static array variable are initialized to null.

class Animal { }
public class ArrayUsage {
	private Animal[] animals; //initialized to null i.e.) animals = null;
}

Array local variable

Local variable should be initialized before using it

public static void main(String[] args) {
	int[] numbers;
       //Compiler ERROR. Must initialize numbers array before using it
	int[] arr = numbers;
}

Array element default values

All array elements are initialized to their default values whether it is an instance, static or local variable.

package com.ibytecode.arrays;
public class ArrayBasics {
	public static void main(String[] args) {
		double[] studentAvgs; //declaring an array reference
		studentAvgs = new double[5]; //creating an array object
		for(double d : studentAvgs)
			System.out.println(d);
	}
}

Output:
0.0
0.0
0.0
0.0
0.0

Array Null Reference

If an array is declared as reference type and if an element is not initialized it will have null value. If you use that null reference by applying a dot operator to access a method or variable it will throw NullPointerException at runtime.

package com.ibytecode.arrays;
class Student
{
	String name;
	int id;
}

public class TwoDReferenceArray {
	public static void main(String[] args) {
		Student[] students = new Student[2];
		Student studentOne = new Student();
		students[0] = studentOne;
		System.out.println(students[1]); //Null reference
		System.out.println(students[1].name);//NullPointerException
	}
}

Output:
null
Exception in thread “main” java.lang.NullPointerException
at com.ibytecode.arrays.TwoDReferenceArray.main(TwoDReferenceArray.java:17)

ArrayIndexOutOfBoundsException

Trying to access index < 0 or index >= size will throw ArrayIndexOutOfBoundsException runtime exception.

double[] numbers = new double[3]; //Index: 0, 1, 2

NegativeArraySizeException

If you specify the size of an array as a negative number then it throws runtime exception (NegativeArraySizeException).

package com.ibytecode.arrays;
public class ArrayBasics {
	public static void main(String[] args) {
		double[] studentAvgs = new double[-5];
}

When you run the above code, you get
Exception in thread “main” java.lang.NegativeArraySizeException
at com.ibytecode.arrays.ArrayBasics.main(ArrayBasics.java:4)

Array and static block

If you make any mistake in initialization block (static block) then it throws ExceptionInInitializerError at runtime.

package com.ibytecode.arrays;
public class StaticInitBlock {
	static double[] numbers = new double[5];
	static
	{
		numbers[5] = 90.0;
	}
	public static void main(String[] args) {	}
}

When you run the above code, you get
java.lang.ExceptionInInitializerError
Caused by: java.lang.ArrayIndexOutOfBoundsException: 5
at com.ibytecode.arrays.StaticInitBlock.(StaticInitBlock.java:7)
Exception in thread “main”

Primitive Array Element

int[] numbers = new int[4];

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

Legal element values: Illegal element values:
byte b = 10;
short s = 20;
char c = 'r';
numbers[0] = b;
numbers[1] = s;
numbers[2] = c;
long l = 100;
numbers[3] = l; //ERROR

Reference Array Element

Array type declared as Class name
class Animal { }
class Cat extends Animal { }
class Dog extends Animal { } 

If an array is declared as reference type then it can hold any element which is a subclass of the declared type, i.e.) which satisfies IS-A relationship.

Animal[] animals = new Animal[4]; 
Legal Element Values Illegal Element Values
Animals[0] = new Animal();
Animals[1] = new Cat()
Animals[2] = new Dog();
Animals[3] = new Object();
Animals[3] = new String();
Animals[3] = new Person();
Array type declared as Interface name
interface LivingBeing {}
class Animal implements LivingBeing {}
class Person implements LivingBeing {}
class Plant implements LivingBeing {}

If an array is declared as interface type then it can hold any object which implements that interface, i.e.) passes IS-A relationship

LivingBeing[] lives = new LivingBeing[4];
Legal Element Values Illegal Element Values
lives[0] = new Animal();
lives[1] = new Person();
lives[2] = new Plant();
lives[3] = new Object();
lives[3] = new String();
lives[3] = new Vehicle();

Primitive Array Assignments

int[] numbers = new int[4];

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.

Legal assignments Illegal assignments
int[] marks = {80,90,70};
numbers = marks;
int[] arr = null;
numbers = arr;
int i = 10;
char[] letters = new char[4];
numbers = letters; //No.ERROR
numbers = i; //No. ERROR

Reference Array Assignments

Example 1: Array type declared as Class name

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

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

Animal[] animals = new Animal[4];
Legal Assignments Illegal Assignments
Cat[] cats = new Cat[5];
Dog[] puppies = new Dog[3];
 //OK. Cat IS-A Animal
animals = cats;
//OK. Dog IS-A Animal
animals = puppies;
Person[] persons;
animals = persons; // No. ERROR

Example 2: Array type declared as Interface name

interface LivingBeing {}
class Animal implements LivingBeing {}
class Person implements LivingBeing {}
class Plant implements LivingBeing {}
class Vehicle {}

Similarly, if an array is declared as interface type then it can reference an array of any type that implements that interface, i.e.) passes IS-A relationship

LivingBeing[] lives = new LivingBeing[4];
Legal Assignments
Animal[] animals = new Animal[4];
Person[] persons = new Person[5];
Plant[] plants = new Plant[3];
//OK. Animal IS-A LivingBeing
lives = animals;
//OK. Person IS-A LivingBeing 
lives = persons;
//OK. Plant IS-A LivingBeing
lives = plants;
Illegal Assignments
//NO. ERROR. Vehicle IS NOT A LivingBeing
lives = vehicles; 
Object[] objects = new Object[3];
lives = objects; //Error
lives = strings //Error

Leave a Comment

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