Arrays in Java


How are Arrays in Java different from C/C++?

An array is a container object that holds a fixed number of values of a single data type. This is different from C/C++ where array name represents an address.

  • Length of an array is fixed when it is created (Note that we are talking about simple arrays here, not dynamic arrays like ArrayList)
  • Since arrays are objects in Java, we can find their length using member length. This is different from C/C++ where we find length using sizeof.
  • A Java array variable is declared like other variables with [] after the data type.
  • The variables in the array are ordered and each have an index beginning from 0.
  • Java array can be also be used as a static field, a local variable or parameter.
  • The size of an array must be specified by an int value and not long or short.

Array can contains primitives data types as well as objects of a class depending on the definition of array. In case of primitives data types, the actual values are stored in contiguous memory locations. In case of objects of a class, the actual objects are stored in heap segment.

Arrays

Creating, Initializing, and Accessing an Array

An array declaration has two components: the array’s type and the array’s name. The Java array variable is declared just like other variables except that [] is added after the type. Like array of int type, we can also create an array of other primitive data types like char, float, double..etc or user defined data type(objects of a class).
Example:

int intArray[]; 
or int[] intArray; //both are valid declarations
byte byteArray[];
short[] shortsArray;
boolean[] booleanArray;
long[] longArray;
float[] floatArray;
double[] doubleArray;
char[] charArray;

MyClass[] myClassArray; //an array of references to objects of the class MyClass 
- a class created by user

As with variables of the types,the declaration of array does not actually create an array that means memory has not been allocated to the declared array.  It simply tells to the compiler that this variable will hold an array of the specified type.

Instantiating an Array in Java

When an array us declared, only a reference of array is created. To actually create or give memory to array, you create an array like this:

int[] intArray;    //declaring array
intArray = new int[20];  // allocating memory to array

OR

int[] arr = new int[20]; // combining both statements in one

Array Literal

In a situation, where the size of the array and variables of array are already known, array literals can be used.

 int[] intArray = new int[]{ 1,2,3,4,5,6,7,8,9,10 }; 
 // Declaring array literal
  • The length of this array determines the length of the created array.
  • There is no need to write the new int[] part in the latest versions of Java

Accessing Java Array Elements using for Loop

Each element in the array is accessed via its index. The index begins with 0 and ends at (total array size)-1. All the elements of array can be accessed using Java for Loop.

// accessing the elements of the specified array
      for(int i = 0; i

Implementation:

 

// Java program to illustrate creating an array of integers, 
// puts some values in the array,
// and prints each value to standard output.
import java.io.*;

class GFG 
{
    public static void main (String[] args) 
    {
         
      // declares an Array of integers.
      int[] arr;
        
      // allocating memory for 5 integers.
      arr = new int[5];
        
      // initialize the first elements of the array
      arr[0] = 10;
        
      // initialize the second elements of the array
      arr[1] = 20;
        
      //so on...
      arr[2] = 30;
      arr[3] = 40;
      arr[4] = 50;
        
      // accessing the elements of the specified array
      for(int i = 0; i < arr.length; i++)
         System.out.println("Element at index " + i +" : "+ arr[i]);
          
    }
}

Output:

Element at index 0 : 10
Element at index 1 : 20
Element at index 2 : 30
Element at index 3 : 40
Element at index 4 : 50

Arrays of Objects

An array of objects is created just like an array of primitive type data items in the following way.

 Student[] arr = new Student[7]; //student is a user-defined class

The studentArray contains seven memory spaces each of size of student class in which the address of seven Student objects can be stored.The Student objects have to be instantiated using the constructor of the Student class and their references should be assigned to the array elements in the following way.

Student arr = new Student[5];

Implementation:

// Java program to illustrate creating an array of objects
import java.io.*;

class Student{
	
	public int roll_no;
	public String name;
	
	Student(int roll_no, String name){
		this.roll_no = roll_no;
		this.name = name;
	}
}

// Elements of array are objects of a class Student.

public class GFG {
	public static void main (String[] args) {
		
	// declares an Array of integers.
	Student[] arr;
		
	// allocating memory for 5 objects of type Student.
	arr = new Student[5];
		
	// initialize the first elements of the array
	arr[0] = new Student(1,"aman");
		
	// initialize the second elements of the array
	arr[1] = new Student(2,"vaibhav");
		
	//so on...
	arr[2] = new Student(3,"shikar");
	arr[3] = new Student(4,"dharmesh");
	arr[4] = new Student(5,"mohit");
		
	// accessing the elements of the specified array
	for(int i = 0; i < arr.length; i++)
		System.out.println("Element at " + i +" : "+ arr[i].roll_no +" "+ arr[i].name);
		
	}
}

Output:

Element at 0 : 1 aman
Element at 1 : 2 vaibhav
Element at 2 : 3 shikar
Element at 3 : 4 dharmesh
Element at 4 : 5 mohit

What happens if we try to access element outside the array size?

Compiler throws ArrayIndexOutOfBoundsException to indicate that array has been accessed with an illegal index. The index is either negative or greater than or equal to size of array.

import java.io.*;

class GFG 
    {
	public static void main (String[] args) 
	{
		int[] arr = new int[2];
	    arr[0] = 10;
	    arr[1] = 20;
	
	    for(int i = 0; i <= arr.length; i++)
		    System.out.println(arr[i]);
	}
}

Runtime error

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
	at GFG.main(File.java:12)

Output:

10
20

Multidimensional Arrays

Multidimensional arrays are arrays of arrays with each element of the array holding the reference of other array. These are also known as Jagged Arrays. A multidimensional array is created by appending one set of square brackets ([]) per dimension. Examples:

int[][] intArray = new int[10][20]; //a 2D array or matrix
int[][][] intArray = new int[10][20][10]; //a 3D array
class multiDimensional
{
    public static void main(String args[])
    {  
        //declaring and initializing 2D array  
        int arr[][] = { {2,7,9},{3,6,1},{7,4,2} };  
        
        //printing 2D array  
        for(int i=0; i< 3 ;i++)
        {  
            for(int j=0; j < 3 ;j++)
            {  
                System.out.print(arr[i][j] + " ");  
            }  
        System.out.println();   
        }  
    }
}  

Output:

2 7 9 
3 6 1 
7 4 2 

Reference: Arrays by Oracle

Leave a Reply