Arrays in java

Let’s learn arrays in java.

Arrays in java

Java arrays is a fixed collection of similar (homogeneous) data-type elements that have contiguous memory location.

For example: int[ ] num = new int[6];

  • Array index value starts from 0. Arrays are dynamically allocated.
  • Also array contain primitive data types (actual values stored in contiguous memory) and objects (array objects are stored in heap) based on definition of array.
  • Array contains a chain of elements stored under one variable name. Hence array occupies consecutive memory location.
  • Array is an object its superclass is Object class.
  • Array size should be defined as integer value.
  • Length of an array can found using member ‘length’.
arrays in java

Types of array in java

There are two types,

  • Single dimensional – 1d array
  • Multidimensional – 2d array and 3d array

Single dimensional array: have either single row or single column. Datatype can be of any like primitive (int, float,char,double) or objects.

Declaration syntax:

datatype[ ] variableName;
datatype variableName[ ];

Example:

// valid 1d array declaration

int b[ ];
int[ ] b; // preffered array declaration
int [ ]b;
int[ ]b;

Above declaration just tells the compiler that “b” will hold array of integer datatype. To connect variable name with actual array of integers use “new” keyword like this,

// array creation

b = new datatype[size];

NOTE: at the time of creation of array it is mandatory to provide array size.

Also read – inheritance in java

Example:

int[ ] b; // declaring an array in java
b = new int[10]; // memory allocation

int[ ] b = new int[10]; // declaring and creating an array

int[ ] b = new int[ ]{1, 2, 3}; // declare, create and initializing array. Here size of array ‘b’ is 3

By “new”, elements in the array will be initialized to zero for numeric types, “false” for boolean and “null” for reference types.


Accessing array elements using for loop

Array index starts with 0 and ends with array size – 1. Array elements can be accessed by its index using “for loop”,

// java array
public class SingleDimensionalDemo 
{
   public static void main(String[] args) 
   {
      // declaring an array and creating an array
      int[ ] arrNum = new int[5]; 
      // java initialize int array
      arrNum[0] = 25; 
      arrNum[1] = 23; 
      arrNum[2] = 15; 
      arrNum[3] = 20; 
      arrNum[4] = 24;
      System.out.println("Single dimensional array : ");
      for(int a = 0; a < arrNum.length; a++)
      {
         System.out.println(arrNum[a]);
      }
   }
}



Output :

Single dimensional array :
25
23
15
20
24


We can also use for-each loop to print java array.

class SingleDimensionalDemo 
{
   public static void main(String[] args) 
   {
      int[ ] arrNum = {25, 23, 15, 20, 24};
      // print array using for-each loop 
      for(int a : arrNum)
      {
         System.out.println(a);
      }
   }
}



Output:

25
23
15
20
24


Arrays class in java

Arrays class is part of java collection framework in java.util package. Class name of single dimensional java array can be obtained using getClass.getName() method on object.

To know arrays class of single dimensional array let’s execute a java program,

class Demo 
{
   public static void main(String[] args) 
   {
      int[ ] b = new int[4];
      System.out.println(b.getClass().getName());
   }
}



Output:

[I


Array of objects

In the above java program we store primitive data types in array. Similarly we can also store objects in array.

Employee[] emp = new Employee[5];

class Employee 
{
   public int empID; 
   public String name; 
   Employee(int empID, String name) 
   { 
      this.empID = empID; 
      this.name = name; 
   }
}

class ArrayObjectsDemo 
{
   public static void main(String[] args) 
   {
      // declaring an array of integers 
      Employee[ ] emp; 

      // allocating memory for 5 objects of type Employee 
      emp = new Employee[5]; 

      // initializing elements of the array 
      emp[0] = new Employee(101,"ajay"); 
      emp[1] = new Employee(201,"vijay");
      emp[2] = new Employee(301,"shikhar"); 
      emp[3] = new Employee(401,"dhoni"); 
      emp[4] = new Employee(501,"mandeep"); 

      // accessing elements of the array 
      for(int a = 0; a < emp.length; a++)
      {
         System.out.println("index " + a + " : " + emp[a].empID + ", " + emp[a].name);
      }
   }
}



Output:

index 0 : 101, ajay
index 1 : 201, vijay
index 2 : 301, shikhar
index 3 : 401, dhoni
index 4 : 501, mandeep


ArrayIndexOutOfBoundsException

Compiler throws ArrayIndexOutOfBoundsException when array accesses with an index out its bound.

public class ArrayException 
{
   public static void main(String[] args) 
   {
      // declaring an integer array
      int arrNum[] = new int[5];
      // initializing elements
      arrNum[0] = 11;
      arrNum[1] = 12;
      arrNum[2] = 13;
      arrNum[3] = 14;
      arrNum[4] = 15;
      arrNum[5] = 16;
      arrNum[6] = 17;
      for(int a = 0; a <= arrNum.length; a++)
      {
         System.out.println(arrNum[a]);
      }
   }
}



Output :

Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException: 5 at ArrayException.main(ArrayException.java:13)

In the above example I have declared integer array. Size of integer array is five.

I am initializing seven elements. This is not possible because size of integer array is 5 and I’m trying to assign seven elements.

So integer array will throw ArrayIndexOutOfBoundsException.


Also read – multidimensional array


Passing array to method

The advantage of passing array to method is that we can reuse the same logic on any array.

public class PassArrayToMethod 
{
   public static void main(String[] args) 
   {
      // declaring and initializing array
      int arrayNumbers[] = {25,23,15,20,24};  
      add(arrayNumbers); // passing array
   }
 
   public static void add(int arrDemo[])
   {  
      int total = 0;
      for(int a = 0; a < arrDemo.length; a++)
      {
         total += arrDemo[a]
      }
      System.out.println(total);    
   }
}



Output:

107


Jagged array in java

An array in which number of columns are not same is jagged array. To create jagged array column size is not specified while declaration.

// declaring jagged array

int[][] num;

// jagged array creation

num = new int[3][];

// here we are declaring number of columns as 4 at 0th index position

num[0] = new int[4];

// similarly here we are declaring number of columns as 2 at 1st index position

num[1] = new int[2];

// lastly here we are declaring number of columns as 3 at 2nd index position

num[2] = new int[3];

Here’s how it looks,

arrays in java

Let’s see demostration of jagged array in java,

public class JaggedArray 
{
   public static void main(String[] args) 
   {
      int[][] arrNumber = new int[3][]; 
      arrNumber[0] = new int[3]; 
      arrNumber[1] = new int[4]; 
      arrNumber[2] = new int[2]; 
      // initializing jagged array 
      int num = 0; 
      for(int a = 0; a < arrNumber.length; a++)
      {
         for(int b = 0; b < arrNumber[a].length; b++)
         {
            arrNumber[a][b] = num++;
         }
      }

      // printing jagged array 
      for(int a = 0; a < arrNumber.length; a++)
      { 
         for(int b = 0; b < arrNumber[a].length; b++)
         { 
            System.out.print(arrNumber[a][b] + " "); 
         } 
         System.out.println(); 
      }
   }
}



Output:

0 1 2
3 4 5 6
7 8


Return array from method

In java, method can also return an array from method. Here’s an example,

class ReturnMethodDemo 
{
   public static void main(String[] args) 
   {
      // calling method 
      int[] arrNum = demo(); 
      // printing the values 
      for(int a = 0; a < arrNum.length; a++)
      {
         System.out.println(arrNum[a] + " ");
      }
   }

   static int[] demo()
   { 
      return new int[]{25, 23, 15, 20, 24}; 
   }
}



Output :

25
23
15
20
24


Also read – array copy in java


Clone method for java arrays

Like variables we cannot copy java array using equal to operator (=). To copy an array, clone() method is used.

Here new array contain copy of original array elements instead of reference. Hence “deep copy” is accomplished.

public class CloneArrayDemo 
{
   public static void main(String[] args) 
   {
      int[] arr = {25,23,15,20,24};
      int[] arrClone = arr.clone();
      // return false as deep copy is implemented 
      System.out.println(arr == arrClone);
      for(int a = 0; a < arrClone.length; a++)
      {
         System.out.print(arrClone[a] + " ");
      }
   }
}



Output:

false
25 23 15 20 24

Similarly what happens in multidimensional array is, new array is created with each and every element having reference to original array but the cloned array will have only subarrays.

public class CloneArrayDemo 
{
   public static void main(String[] args) 
   {
      int[][] arr = {{25,23,15},{20,24}};
      int[][] arrClone = arr.clone(); 
      System.out.println(arr == arrClone); 
      // return true as shallow copy is implemented
      System.out.println(arr[0] == arrClone[0]); 
      System.out.println(arr[1] == arrClone[1]);
   }
}



Output:

false
true
true