Arrays in java

Let’s learn Arrays in java.

Arrays in java

Arrays are indexed based collection of fixed number of homogeneous data type elements. Arrays are fixed in size.

Example: int[ ] num = new int[6];

In the above example we’ve defined an array called ‘num’ of type integer. Let’s see a java program on arrays.

class ArrayDemoProgram 
{
    public static void main(String[] args)
    {
        int[] num = {6, 52, 98, 35, 48, 36};
        for(int i = 0; i < num.length; i++)
        {
            System.out.println("Element at index " + i + " is " + num[i]);
        }
    }
}

Output:

Element at index 0 is 6
Element at index 1 is 52
Element at index 2 is 98
Element at index 3 is 35
Element at index 4 is 48
Element at index 5 is 36


Single dimensional array in java

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

Syntax:

datatype[] variableName;

Valid single dimensional array declaration.

int b[];

int[] b; // preffered array declaration

int []b;

int[]b;

Array creation: we have to declare the size of the array at the time of creation. For example: b = new int[6];

To declare and create array in single line: int[] b = new int[6];

Declaration, creation and initialization of an array in java:

int[] b = {6, 15, 24}; OR

int[] b = new int[] {6, 15, 24};

Array elements will be initialized to zero for int data type, “false” or “true” for boolean and “null” for reference types.


Array length in java

To determine length of an array or how many elements an array has, use length property of Arrays class. Using this property we can determine size of an array.

arrays in java

Accessing 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 AccessingArrayElements
{
   public static void main(String[] args)
   {
      int[] arrNum = {25, 23, 15, 20, 24};
      for(int a = 0; a < arrNum.length; a++)
      {
         System.out.println(arrNum[a]);
      }
   }
}

Output:

25
23
15
20
24


We can also use for-each loop to access array elements.

class AccessingArrayElements
{
   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


Array of objects in java

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

class Employee
{
    private String name;
    private int empAge;
	
    Employee(String name, int empAge)
    {
        this.name = name;
        this.empAge = empAge;
    }
    public void setName(String name)
    {
        this.name = name;
    }
    public void setAge(int empAge)
    {
        this.empAge = empAge;
    }
    public void display()
    {
        System.out.println("Employee name : " + this.name);
        System.out.println("Employee age : " + this.empAge);
    }
}

class ArrayObjectsDemo
{
    public static void main(String[] args)
    {
        // creating array to store objects of type Employee 
        Employee[] emp = new Employee[2];
        emp[0] = new Employee("abc", 24);
        emp[1] = new Employee("xyz", 26);
        for(int a = 0; a < emp.length; a++)
        {
            emp[a].display();
            System.out.println("");
        }
    }
}

Output:

Employee name : abc
Employee age : 24

Employee name : xyz
Employee age : 26


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)
   {
      int[] arrNum = {11, 12, 13, 14, 15, 16, 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.


Advantages of arrays

Arrays makes the code optimized. We can retrieve data efficiently. We can access and get any data located at an index position.

Disadvantages of arrays

In arrays we can store only fixed size of elements. It does not grow its size at runtime.