Arrays in java

Let’s learn arrays in java.

Arrays in java

Java array is an object which holds fixed number of elements of similar type.

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

  • Array index value starts from 0.
  • 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 superclass is Object.
  • Array size should be defined as integer value.
  • Length of an array can be found using member ‘length’.

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 datatypes(int, float, char, double) or objects.

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 to compiler that “b” will hold array of datatype integer.

Also read – inheritance in java

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 = new int[10]; // combining above two statements

int[ ] b = new int[ ]{1, 2, 3}; // array literal


Arrays in java: array length java

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

arrays in java

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 java arrays.

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 in java: 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


Arrays in java: 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)
   {
      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.


Also read – 2d array in java

Also read – multidimensional array in java


Arrays in java: Passing array to method

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

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


Arrays in java: 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


Also read – system array copy in java