Arrays in java

Let’s learn Arrays in java.

Arrays in java

Array in java is a data structure that allows you to store sequence of values, of same type.

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

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

public class Main
{
   public static void main(String[] args)
   {
      int[] num = new int[6];
      for(int i = 0; i < num.length; i++)
      {
         num[i] = i * 10;
      }
      for(int i = 0; i < num.length; i++)
      {
         System.out.println("Element " + i + ", value is " + num[i]);
      }
   }
}

Output:

Element 0, value is 0
Element 1, value is 10
Element 2, value is 20
Element 3, value is 30
Element 4, value is 40
Element 5, value is 50


NOTE:

  • Arrays are zero indexed. That is an array with ‘n’ elements is indexed from 0 to n – 1.
  • Default values of numeric array elements are set to ‘zero’. For boolean array elements it would be initialized to ‘false’ and for String objects it would be ‘null’.
  • If user tries to access index that is out of range compiler will throw an ArrayIndexOutOfBoundsException.
  • The ‘new’ keyword is used to create an array and initialize the array elements to their default values.
  • Array size should be defined as integer value.
  • Length of an array can be found using member ‘length’.

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;
datatype variableName[];

Valid single dimensional array declaration

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

Array elements will be initialized to zero for numeric types, “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


Array class in java

Array 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 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)
   {
      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.


Passing an array as a method

The advantage of passing an array as a method is that we can reuse the same logic.

class PassArrayToMethod
{
   public static void main(String[] args)
   {
      // declaring and initializing array
      int[] arrayNumbers = {25,23,15,20,24};
      add(arrayNumbers); // passing the 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


Return array from method

Let’s learn how to return array from method in java. To return array from method reference to an array is 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