Arrays in java

Let’s learn arrays in java.

Arrays in java

Java array is a fixed collection of similar or 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 be found using member ‘length’.

Types of array in java

There are two types,

  • Single dimensional or one dimensional array in java – 1d array
  • Multidimensional – 2d array and 3d array

Single dimensional array or one dimensional array in java:

One dimensional array in java is an array declared with single index. Datatype can be of any like primitive (int, float,char,double) or objects.

Syntax:

datatype[] variableName;
datatype variableName[];

Let’s understand and learn arrays in java with the help of an example.

Example:

// valid 1d array declaration

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

Above declaration just tells to 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];

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

int[ ] b; // declaring an array in java
b = new int[10]; // allocating memory for array ‘b’

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

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

Also read – inheritance in java

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

Example:

class OnedimensionalExample
{
   public static void main(String args[])
   {    
      int[] num = new int[3];
      num[0] = 2;
      num[1] = 4;
      num[2] = 6;
      System.out.println("One dimensional array elements: ");    
      System.out.println(num[0]);
      System.out.println(num[1]);
      System.out.println(num[2]);
   }
} 


Output:

One dimensional array elements:

2

4

6


Accessing one dimensional array elements using for loop

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

public class SingleDimensionalDemo 
{
   public static void main(String[] args) 
   {
      // declaring 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("One dimensional array in java: ");
      for(int a = 0; a < arrNum.length; a++)
      {
         System.out.println(arrNum[a]);
      }
   }
}



Output :

One dimensional array in java:
25
23
15
20
24


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

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 array or one dimensional 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


Java array of objects

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

Syntax:

Class[] obj = new Class[array_length]

class Employee
{
   public int empID; 
   public int empSalary; 
   public void setValue(int ID, int salary) 
   { 
      empID = ID; 
      empSalary = salary; 
   }
   public void printValue()
   {
      System.out.println("Employee ID: " + empID);
      System.out.println("Employee salary: " + empSalary);
   }
}

public class ArrayObjectsDemo 
{
   public static void main(String[] args) 
   {
      Employee emp[] = new Employee[1];
      emp[0] = new Employee();
      emp[0].setValue(1001, 25000);
      System.out.println("Employee details: ");
      emp[0].printValue();
   }
}



Output:

Employee details:
Employee ID: 1001
Employee salary: 25000


java.lang.ArrayIndexOutOfBoundsException in java

Compiler throws java.lang.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 java.lang.ArrayIndexOutOfBoundsException.


Also read – 2d array in java


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
      System.out.println("Jagged array in java: ");
      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:

Jagged array in java:

0 1 2
3 4 5 6
7 8


Return array from method

Let’s learn how to return array from method in java. To do that reference to an array can be returned from method. Let’s see java program,

public class ReturnArrayFromMethod
{
   public static void main(String[] args) 
   {
      // number of elements in an array
      final int NUMBER = 6;
      // creating array
      int[] arrNumbers;
      // reference the array
      arrNumbers = arrMethod(NUMBER);
      // Display the values in the array.
      for(int a = 0; a < arrNumbers.length; a++)
      {
         System.out.print(arrNumbers[a] + " ");
      }
   }

   public static int[] arrMethod(int num)
   {
      int[] arr = new int[num];
      for(int a = 0; a < arr.length; a++)
      {
         arr[a] = (int) (Math.random() * 10);
      }
      return arr;
   }
}


Output:

8 0 7 6 1 9


Also read – system array copy in java


Array copy using clone() method

Like variables we cannot copy 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 ArrayCloneMethod
{
   public static void main(String[] args) 
   {
      int[] arrGiven = {2, 4, 6};
      // copy the elements of arrGiven[] to arrClone[] 
      int[] arrClone = arrGiven.clone();
      System.out.println("Given array: "); 
      for(int a = 0; a < arrGiven.length; a++)
      {
         System.out.print(arrGiven[a] + " ");
      }
      System.out.println("\nArray copy using clone() method: "); 
      for(int a = 0; a < arrClone.length; a++)
      {
         System.out.print(arrClone[a] + " ");
      }
   }
}



Output:

Given array:
2 4 6
Array copy using clone() method:
2 4 6

java array length

To determine length of an array there is length field available in array. Using this we can determine size of array.

arrays in java
public class JavaArrayLength 
{
   public static void main(String[] args) 
   {
      int[] arrNumber = new int[6];
      System.out.println("Size of the array is: " + arrNumber.length);
   }
}


Output:

Size of the array is: 6

Now let’s see another example,

public class JavaArrayLength
{
   public static void main(String[] args) 
   {
      String[] strDemo = { "hello", "world", "java" };
      System.out.println("Size of the array is: " + strDemo.length);
   }
}


Output:

Size of the array is: 3