Java Array

An array is a collection of similar type of elements that have a contiguous memory location.Java array is an object which contains elements of a similar data type. It is a data structure where we store similar elements. We can store only a fixed set of elements in a Java array.

java array
What are Arrays in Java?

Arrays are objects which store multiple variables of the same type. It can hold primitive types as well as object references. In fact most of the collection types in Java which are the part of java.util package use arrays internally in their functioning. Since Arrays are objects, they are created during runtime .The array length is fixed.

Advantages
  • Code Optimization: It makes the code optimized, we can retrieve or sort the data efficiently.

  • Random access: We can get any data located at an index position.

Disadvantages
  • Size Limit: We can store only the fixed size of elements in the array. It doesn't grow its size at runtime. To solve this problem, collection framework is used in Java which grows automatically.

Features of Array
  1. Arrays are objects
  2. They can even hold the reference variables of other objects
  3. They are created during runtime
  4. They are dynamic, created on the heap
  5. The Array length is fixed
Types of Array in java

There are two types of array.

  • Single Dimensional Array
  • Multidimensional Array
Single Dimensional Array in Java

Syntax to Declare an Array in Java

dataType[] arr; (or) dataType []arr; (or) dataType arr[];
Instantiation of an Array in Java
arrayRefVar=new datatype[size];

Ex 1: Declaring an array which holds elements of integer type.

int aiMyArray[];

The above statement creates an array reference on the stack.

Different way of declaring an array –

Both the below statements are valid and same!!

int []aiMyArray; int aiMyArray[];
Compilation error –

Below statement would cause a compilation error as compiler (JVM) doesn’t allocate object until it is actually instantiated to array object.

int aiFirstArray[] = new int[6];

The above statement creates an array of size 6 on the heap. For creation of Array object the JVM needs to know the size of the space to be allocated to the object, so the size need to be specified succeeding the new key word.

If you observe, all the elements of the array will be initialized to 0 as it’s created on the heap. If you want some other values instead of default values you need to specify as follows

int aiFirstArray[]={1,2,3,4,5,6};

The above statement declares, constructs and initializes the array.

Array Usage

The array elements can be accessed with the help of the index. aiFirstArray[0] refers to 1 ,aiFirstArray[1] refers to 2 etc. You can access up to aiFirstArray[n-1] where n is the size of the array. Accessing the array with an index greater than or equal to the size of the array leads to NullPointer Exception.

How to get the size of array?

aiFirstArray.length gives the size of the Array.

Ex 3: The below example initializes the array elements to 1,2,3,4,5,6 and prints them.

class ArrayInitializing{ public static void main(String args[]){ int aiFirstArray[] = new int[6]; for(int i=0;i<aiFirstArray.length;i++){ aiFirstArray[i]=i+1; } for(int i=0;i<aiFirstArray.length;i++){ System.out.println(aiFirstArray[i]); } } }
Garbage collection and Arrays
aiFirstArray=null;

The above statement makes the array to point to null, means the array object which was on the heap is ready for garbage collection. Referring to array object now gives a NullPointer Exception.

Example of Java Array

Simple example of java array, where we are going to declare, instantiate, initialize and traverse an array.

//Java Program to illustrate how to declare, instantiate, initialize //and traverse the Java array. class Testarray{ public static void main(String args[]){ int a[]=new int[5];//declaration and instantiation a[0]=100;//initialization a[1]=200; a[2]=300; a[3]=400; a[4]=500; //traversing array for(int i=0;i<a.length;i++)//length is the property of array System.out.println(a[i]); }}


Output:
100 200 300 400 500
Declaration, Instantiation and Initialization of Java Array

We can declare, instantiate and initialize the java array together by:

int a[]={33,3,4,5};//declaration, instantiation and initialization
Another simple Example of Java Array
//Java Program to illustrate the use of declaration, instantiation //and initialization of Java array in a single line class Testarray1{ public static void main(String args[]){ int a[]={31,36,1,2};//declaration, instantiation and initialization //printing array for(int i=0;i<a.length;i++)//length is the property of array System.out.println(a[i]); }}


Output:
31 36 1 2
Passing Array to Method in Java

We can pass the java array to method so that we can reuse the same logic on any array.

Simple example to get the minimum number of an array using a method.

//Java Program to demonstrate the way of passing an array //to method. class Testarray2{ //creating a method which receives an array as a parameter static void min(int arr[]){ int min=arr[0]; for(int i=1;i<arr.length;i++) if(min>arr[i]) min=arr[i]; System.out.println(min); } public static void main(String args[]){ int a[]={31,36,1,2};//declaring and initializing an array min(a);//passing array to method }}


Output:
1
Anonymous Array in Java

Java supports the feature of an anonymous array, so you don't need to declare the array while passing an array to the method.

//Java Program to demonstrate the way of passing an anonymous array //to method. public class TestAnonymousArray{ //creating a method which receives an array as a parameter static void printArray(int arr[]){ for(int i=0;i<arr.length;i++) System.out.println(arr[i]); } public static void main(String args[]){ printArray(new int[]{31,36,1,2});//passing anonymous array to method }}


Output:
31 36 1 2
Returning Array from the Method

We can also return an array from the method in Java.

//Java Program to return an array from the method class TestReturnArray{ //creating method which returns an array static int[] get(){ return new int[]{10,20,30,40,50}; } public static void main(String args[]){ //calling method which returns an array int arr[]=get(); //printing the values of an array for(int i=0;i<arr.length;i++) System.out.println(arr[i]); }}


Output:
10 20 30 40 50
ArrayIndexOutOfBoundsException

The Java Virtual Machine (JVM) throws an ArrayIndexOutOfBoundsException if length of the array in negative, equal to the array size or greater than the array size while traversing the array.

//Java Program to demonstrate the case of //ArrayIndexOutOfBoundsException in a Java Array. public class TestArrayException{ public static void main(String args[]){ int arr[]={10,20,30,40}; for(int i=0;i<=arr.length;i++){ System.out.println(arr[i]); } }}


Output:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4 at TestArrayException.main(TestArrayException.java:5) 10 20 30 40
Multidimensional Array in Java

In such case, data is stored in row and column based index (also known as matrix form).

Syntax to Declare Multidimensional Array in Java

dataType[][] arrayRefVar; (or) dataType [][]arrayRefVar; (or) dataType arrayRefVar[][]; (or) dataType []arrayRefVar[];
Example to instantiate Multidimensional Array in Java
int[][] arr=new int[3][3];//3 row and 3 column
Example to initialize Multidimensional Array in Java
arr[0][0]=1; arr[0][1]=2; arr[0][2]=3; arr[1][0]=4; arr[1][1]=5; arr[1][2]=6; arr[2][0]=7; arr[2][1]=8; arr[2][2]=9;

Multidimensional arrays are arrays of arrays with each element of the array holding the reference of other array. These are also called Jagged Arrays.

Ex
int aiMdArray[][]=new int [2][];

The above statement creates an array where it has two elements pointing to null. You need not mention any thing in the second square brace as the individual arrays can be created later.

aiMdArray[0]=new int [2];

The above statement initializes the first element to a new array of 2 elements.

aiMdArray[0][0]=10;

The above statement initializes the first element of the first array to 10.

Array of References

Arrays in Java can also hold object references apart from primitives. Let us go through an example which explains Array of Objects.

Ex: consider a class Employee which has a sub class Trainee

class Employee{} class Trainee extends Employee{}

Consider this statement:

Employee emp[]=new Employee[3];

The above statement creates only an array of 3 elements which holds 3 employee references emp[0], emp[1], emp[2]. Note that the employee objects are not yet created. Referring to employee objects leads to Runtime Exception.

The following code initializes the employee objects

for(int i=0;i<emp.length;i++){ emp[i]=new Employee(); }

Since the parent class reference can also point to child class objects:

for(int i=0;i<emp.length;i++){ emp[i]=new Trainee(); }

Consider an Interface Salary which is being implemented by Employee.

interface Salary{} class Employee implements Salary{}

We know that Interface cannot be instantiated, but the reference can be used to point to the objects of the classes that implements it. So we can have a code like the following one –

Salary sal[]=new Salary[2]; sal[0]=new Employee(); sal[1]=new Employee();
Example of Multidimensional Java Array

Simple example to declare, instantiate, initialize and print the 2Dimensional array.

//Java Program to illustrate the use of multidimensional array class Testarray3{ public static void main(String args[]) { //declaring and initializing 2D array int arr[][]={{1,2,3},{2,4,5},{4,4,5}}; //printing 2D array for(int i=0;i<3;i++){ for(int j=0;j<3;j++){ System.out.print(arr[i][j]+" "); } System.out.println(); } } }


Output:
1 2 3 2 4 5 4 4 5
Jagged Array in Java

If we are creating odd number of columns in a 2D array, it is known as a jagged array. In other words, it is an array of arrays with different number of columns.

//Java Program to illustrate the jagged array class TestJaggedArray{ public static void main(String[] args){ //declaring a 2D array with odd columns int arr[][] = new int[3][]; arr[0] = new int[3]; arr[1] = new int[4]; arr[2] = new int[2]; //initializing a jagged array int count = 0; for (int i=0; i<arr.length; i++) for(int j=0; j<arr[i].length; j++) arr[i][j] = count++; //printing the data of a jagged array for (int i=0; i<arr.length; i++){ for (int j=0; j<arr[i].length; j++){ System.out.print(arr[i][j]+" "); } System.out.println();//new line } } }


Output:
0 1 2 3 4 5 6 7 8
What is the class name of Java array?

In Java, an array is an object. For array object, a proxy class is created whose name can be obtained by getClass().getName() method on the object.

//Java Program to get the class name of array in Java class Testarray4{ public static void main(String args[]){ //declaration and initialization of array int arr[]={4,4,5}; //getting the class name of Java array Class c=arr.getClass(); String name=c.getName(); //printing the class name of Java array System.out.println(name); } }


Output:
I
Copying a Java Array

We can copy an array to another by the arraycopy() method of System class.

Syntax of arraycopy method
public static void arraycopy( Object src, int srcPos,Object dest, int destPos, int length )
Example of Copying an Array in Java
//Java Program to copy a source array into a destination array in Java class TestArrayCopyDemo { public static void main(String[] args) { //declaring a source array char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f', 'e', 'i', 'n', 'a', 't', 'e', 'd' }; //declaring a destination array char[] copyTo = new char[7]; //copying array using System.arraycopy() method System.arraycopy(copyFrom, 2, copyTo, 0, 7); //printing the destination array System.out.println(String.valueOf(copyTo)); } }


Output:
caffein
Addition of 2 Matrices in Java

Simple example that adds two matrices.

//Java Program to demonstrate the addition of two matrices in Java class Testarray5{ public static void main(String args[]) { //creating two matrices int a[][]={{1,3,4},{3,4,5}}; int b[][]={{1,3,4},{3,4,5}}; //creating another matrix to store the sum of two matrices int c[][]=new int[2][3]; //adding and printing addition of 2 matrices for(int i=0;i<2;i++){ for(int j=0;j<3;j++){ c[i][j]=a[i][j]+b[i][j]; System.out.print(c[i][j]+" "); } System.out.println();//new line } } }


Output:
2 6 8 6 8 10
Multiplication of 2 Matrices in Java

In the case of matrix multiplication, a one-row element of the first matrix is multiplied by all the columns of the second matrix which can be understood by the image given below.

Multiplication of 2 Matrices

Simple example to multiply two matrices of 3 rows and 3 columns.

//Java Program to multiply two matrices public class MatrixMultiplicationExample{ public static void main(String args[]){ //creating two matrices int a[][]={{1,1,1},{2,2,2},{3,3,3}}; int b[][]={{1,1,1},{2,2,2},{3,3,3}}; //creating another matrix to store the multiplication of two matrices int c[][]=new int[3][3]; //3 rows and 3 columns //multiplying and printing multiplication of 2 matrices for(int i=0;i<3;i++){ for(int j=0;j<3;j++){ c[i][j]=0; for(int k=0;k<3;k++) { c[i][j]+=a[i][k]*b[k][j]; }//end of k loop System.out.print(c[i][j]+" "); //printing matrix element }//end of j loop System.out.println();//new line } } }


Output:
6 6 6 12 12 12 18 18 18



Instagram