Java Array – An Ultimate Guide for a Beginner

Till now, you have been working with data in Java programs in a simple manner. But now, one question arises: how would you create classes/objects for a situation where you have to deal with a collection of similar data items?

For example, suppose you have to handle marks of 20 students. That is, you have to handle 20 marks variables. How would you do so?  We will have to declare and initialize 20 marks variables. Similarly, if there are 100 students we will have to do the same for 100 students.

To simplify this, Java offers a reference data type called arrays. An array can hold multiple values of the same type.

In this article, we will discuss the arrays in Java along with their types.

Java Array

An Array, one of the data structures in Java, is a collection of variables of the same type that are referenced by a common name. Arrays consist of contiguous memory locations. The first address of the array belongs to the first element and the last address to the last element of the array.

Some points about arrays:

  • Arrays can have data items of simple types such as int or float, or even user-defined datatypes like structures and objects.
  • The common data type of array elements is known as the base type of the array.
  • Arrays are considered as objects in Java.
  • The indexing of the variable in an array starts from 0.
  • Like other variables in Java, an array must be defined before it can be used to store information.
  • Arrays in Java are stored in the form of dynamic allocation in the heap area.
  • We can find the length of arrays using the member ‘length’.
  • The size of an array must be an int value.
  • Object class is a superclass of the Array.
  • Array implements the two interfaces: Serializable and Cloneable.

The need for an Array

Arrays are very useful in cases where many elements of the same data types need to be stored and processed. It is also useful in real-time projects to collect the same type of objects and send all the values with a single method call.

Follow TechVidvan on Google & Stay updated with latest technology trends

Types of Java Arrays

1. Single dimensional arrays/one-dimensional array – comprised of finite homogeneous elements.

2. Multi-dimensional arrays – comprised of elements, each of which is itself an array.

The simplest of multidimensional arrays is a two-dimensional array. However, Java allows arrays of more than two dimensions. The compiler you use can determine the exact limit of dimensions.

We will discuss in detail about single-dimensional and two-dimensional arrays:

1. Single Dimensional Arrays

The simplest form of an array is a single-dimensional array. It has elements in a single dimension. Such as a variable, method, and class, we can give a name to the array. And, we refer to array elements by their subscripts or indices.

1.1. Declaring one-dimensional arrays

Like other definitions, an array definition specifies a variable type and a name along with one more feature size to specify how many items the array will contain.

The valid syntax for array declaration can be –

data-type array_name [ ];
data-type [ ] array_name;

Example –

int daysInMonth [ ];
char [ ] lettersInSentence;
double salaryOfEmployees [ ];
String progLanguages[ ];
1.2. Initializing one-dimensional arrays

After declaring an array, we allocate the memory to the array with the help of a new operator and assign the memory to the array variable. So, let us see how we can initialize arrays in different ways. The variable size of the array should be of constant integer type without any sign (+ or -).

The valid syntax for array initialization can be –

array_name = new data-type [size of array];
array_name = new data-type {elements of array using commas};

Example –

daysInMonth = new int [100];
lettersInSentence = new char[5];
salaryOfEmployees = new double[ ] {10000, 50000, 30000, 25000 };
progLanguages = { “C”, “Java”, “Ruby”, “Python”, “PHP” };

We can also combine declaration and initialization and write as follows:

int daysInMonth[ ] = new int [100];
char [ ] lettersInSentence = new char[5];

Note – Java stores the value of each element with 0 if the elements of an array are not given.

The below diagram shows the illustration of one-dimensional arrays.

one dimensional array in java

1.3. Accessing or using one-dimensional arrays

An array element may be accessed or used in a place where an ordinary variable of the same type may be used. An array element is addressed or referred using the array name followed by an integer subscript or index in square brackets[ ].

For example, myArray[2]; will give us the third element of the array myArray.

We can access each element of the array using Java for loop.

For example:

// accessing all elements of the specified array
for (int i = 0; i < myArray.length; i++)
   System.out.println("Element at index " + i + " : "+ myArray[ i ]);

Code Snippet to illustrate declaring, initializing, and accessing array:

package com.TechVidvan.JavaArrays;
public class OneDimesionalArray
{
  // Java program to illustrate store and print marks of 5 students
  public static void main (String[] args)
  {
    // declaring an Array of integers.
    int[] marks;

    // allocating memory for 5 integers.
    marks = new int[5];
    
    // initializing the first element of the array
    marks[0] = 78;
    // initializing the second element of the array and so on..
    marks[1] = 85;
    marks[2] = 97;
    marks[3] = 66;
    marks[4] = 70;

    // accessing the elements of the specified array
    for (int iterator = 0; iterator < marks.length; iterator++)
    System.out.println("Marks of Student " + (iterator+1) +": "+ marks[iterator]);
  }
}

Output:

Marks of Student 1: 78
Marks of Student 2: 85
Marks of Student 3: 97
Marks of Student 4: 66
Marks of Student 5: 70

We can also access or use the elements of Java array using a for-each loop. The for-each loop in Java is used to print the array elements one after the other. It holds an array element in a variable and then executes the loop body.

The syntax of the for-each loop is:

for(data_type variable:array)
{
        //body of the loop
}

Code Snippet to access an array using a for-each loop:

package com.techvidvan.javaarrays;
public class OneDimesionalArray
{
  public static void main (String[] args)
  {
    // declaring an Array of integers.
    int[] marks = new int[5];
    // initialize elements of the array
    marks[0] = 78;
    marks[1] = 85;
    marks[2] = 97;
    marks[3] = 66;
    marks[4] = 70;

    // accessing the elements of the specified array
    System.out.println("Marks of 5 Students:");
    for (int iterator :marks)
      System.out.println(iterator);
  }
}

Output:

Marks of 5 Students:
78
85
97
66
70
Passing an Array to a method or function

We can also pass the Java array to methods or functions, just like normal variables. Passing an array to method helps us to reuse the same logic on any array.

When we pass an array as an argument to a method, it is actually the address of the first element of the array (base address) which is passed as a reference. Therefore, if we make any changes to this array in the method, it will affect the array.

Syntax:

When we pass an array to a method, we specify the name of the array without any square brackets within the method call.

int[] num = new int[10]; 	//array declaration
methodName (int [] x) 		//passing an array to method
{
  //method body
}
methodName (num);  			//calling the method

Code to illustrate the passing of an array to a method:

package package com.techvidvan.javaarrays;;
public class PassingArrayToMethod
{
  public static void main (String[] args)
  {
    int myArray[] = { 1, 2, 3, 4, 5, 6 }; //creating array
    System.out.println("Array before passing to a method:");
    {
      for(int i=0; i<myArray.length;i++)
      {
        System.out.println(myArray[i]);
      }
    }
    System.out.println("Array after passing to a method:");
    //calling method by passing myArray to them.
    manipulateArray(myArray);
    display(myArray);
  } //main method ends here
  static void manipulateArray(int a[]) //declaring method
  {
    for(int i=0; i<a.length;i++)
    {
      a[i] = a[i]*10;
    }
  }
  static void display(int a[]) //declaring method
  {
    System.out.println("Displaying array elements after 					multiplying each element by 10:");
    for(int i=0; i<a.length;i++)
    {
      System.out.println( a[i] );
    }
  }
}

Output:

Array before passing to a method:
1
2
3
4
5
6
Array after passing to a method:
Displaying array elements after multiplying each element by 10:
10
20
30
40
50
60

Array Members

Arrays are the object of a class, and the class ‘Object’ is the direct superclass of arrays. The members of an array are:

  • The field public final length which stores the number of elements of the array. length can be either zero or positive, but never be negative.
  • All the members are inherited from their superclass ‘Object’. But, there is a method clone() that is not inherited from Object class.
  • The public method clone() overrides the clone method in class Object and does not throw any checked exceptions.

1.4. Memory Representation of single-dimensional arrays

Single-dimensional arrays are lists of data of the same type and their elements are stored in a contiguous memory location in their index order. For instance, an array age of type int with 5 elements is declared as:

int age[ ] = new int[5 ];

Or as,

int[ ] age = new int[5 ];

This array will have age[0] at the first allocated memory location, age[1] at the next memory location and so on. Since age is an int type array, the size of each element is 4 bytes. If the starting memory location of array age is 5000, then it will be represented in the memory location as follows:

single dimensional memory representation

ArrayIndexOutOFBoundExceptions

We can address or refer to each element of the array using the name of the array with subscripts or indexes 0, 1, 2….., size-1, where size is the total number of elements of the array. That is if an array is arr[6], then legal array elements would be:

arr[0] , arr[1], arr[2], arr[3], arr[4], arr[5]

Subscripts or index which are less than zero or greater than or equal (>=) to a number of elements are illegal since they do not correspond to real memory locations in the array. For example, the following are some illegal subscripts for above-mentioned array (that is, all other than legal subscripts):

arr[-5], arr[-1], arr[8], arr[7] etc.

These subscripts are said to be out-of-bounds. Reference to an out-of-bounds indexing produces an out-of-bounds exception, and the program will crash if the exception is not handled.

Note: The subscripts other than 0…..n-1 (both inclusive limits) for an array having n elements, are called out-of-bound subscripts.

Code to understand OutOfBoundsException:

package package com.techvidvan.javaarrays;;
public class OneDimesionalArray
{
  public static void main (String[] args)
  {
    int[] arr = new int[5];
    arr[0] = 10;
    arr[1] = 20;
    arr[2] = 10;
    arr[3] = 20;
    arr[4] = 10;
    // trying to access arr[5] will give an exception
    for (int i = 0; i <= 5; i++)
      System.out.println(arr[i]);
  }
}

Output:

10
20
10
20
10
Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5
at project1/package com.techvidvan.javaarrays;.OneDimesionalArray.main(OneDimesionalArray.java:19)

Multi-Dimensional Arrays

Till now, we have worked on arrays with a single dimension. Now we will move to the concept of multi-dimensional arrays that have multiple or more than one dimension.

Multi-dimensional arrays are arrays of arrays in which each element of the array holds the reference of other arrays. We can also call them Jagged Arrays. The most commonly used multi-dimensional array is a two-dimensional array.

A two-dimensional array is an array in which each element is a one-dimensional array.

For example, a two-dimensional array myArray [ M ][ N ] is an M by N table with M rows and N columns containing M N elements.

By multiplying the number of rows with the number of columns we can determine the number of elements in a two-dimensional array. For example, the number of elements in an array arr [7][9] is calculated as 7 9 = 63.

Following diagram illustrates a multi-dimensional array:

multi dimensional java array

Syntax of declaring two-dimensional arrays is:

type array-name [ ][ ]= new type[number of rows] [number of columns];

or,

type [ ][ ] array-name = new type[number of rows] [number of columns];

Example:

int myArray [ ] [ ] = new int [5] [12] ;

or,

int[ ] [ ] myArray = new int[5] [12] ;

The array myArray has 5 elements myArray [0], myArray[1], myArray[3], and myArray[4], each of which itself is an int array with 12 elements.

The elements of myArray can be referred to as myArray[0][0], myArray[0][1], myArray[0][2],…….., myArray[0][12], myArray [1][0], ……. and so forth.

Code to understand two-dimensional arrays:

package package com.techvidvan.javaarrays;
public class TwoDimensionalArrays
{
  public static void main (String[] args)
  {
    //declaring and initializing a two-dimensional array
    int[][] myArray = new int[3][3];

    myArray[0][0]=1;
    myArray[0][1]=2;
    myArray[0][2]=3;
    myArray[1][0]=4;
    myArray[1][1]=5;
    myArray[1][2]=6;
    myArray[2][0]=7;
    myArray[2][1]=8;
    myArray[2][2]=9;

    //printing a two-dimensional array
    for(int i=0;i<3;i++)
    {
      for(int j=0;j<3;j++)
      {
        System.out.print(myArray[i][j]+" ");
      }
      System.out.println();
    }
  }
}

Output:

1 2 3
4 5 6
7 8 9

Cloning of arrays

There are 2 different types of cloning of arrays, they are as follows –

1. Cloning single-dimensional arrays

Cloning a single-dimensional array, such as Object[ ], means performing a “deep copy” operation in which a new array is created, which contains copies of the elements of the original arrays. We can perform cloning of arrays in Java with the help of the clone() method:

Cloning is necessary when we want to create an object with a similar state as the original object. In short, with the help of Cloning single-dimension, we can create the copy of the original object.

Code to illustrate cloning of one-dimensional arrays:

package com.techvidvan.javaarrays;
import java.util.Arrays;
public class Cloning
{
  public static void main(String[] args)
  {
    int intArray[] = { 50, 60, 70 };
    int clonedArray[] = intArray.clone();

    // will print false as a deep copy is created for a one-dimensional array
    System.out.println(intArray == clonedArray);

    System.out.print("Printing cloned array:\n");
    for (int i = 0; i < clonedArray.length; i++)
    {
      System.out.print(clonedArray[i]+" ");
    }
  }
}

Output:

false
Printing cloned array:
50 60 70

single dimensional cloning array

2. Cloning of multi-dimensional arrays

Cloning a multi-dimensional array, such as Object[ ][ ], means performing a “shallow copy”. It creates only a single new array with each element of the array as a reference to an element of the original array.

In the cloning of multi-dimensional arrays, subarrays are shared, that is, they are not cloned.

Code to illustrate cloning of multi-dimensional arrays:

package com.techvidvan.javaarrays;
import java.util.Arrays;
public class Cloning
{
  public static void main(String[] args)
  {
    int intArray[][] = {{1,2,3},{4,5,6}};
    int clonedArray[][] = intArray.clone();

    // will print false
    System.out.println(intArray == clonedArray);

    // it will print true as a shallow copy is created and sub-arrays are //shared
    System.out.println(intArray[0] == clonedArray[0]);
    System.out.println(intArray[1] == clonedArray[1]);

    System.out.println("\nPrinting cloned array:");
    for (int i = 0; i < 2; i++)
    {
      for (int j = 0; j < 3; j++)
      {
        System.out.print(clonedArray[i][j]+ " ");
      }
      System.out.println();
    }
  }
}

Output:

false
true
true
Printing cloned array:
1 2 3
4 5 6

multi dimensional cloning array

The Array class in Java

The package java.util.Arrays contain the Array class to perform operations on Arrays. It provides many static methods which are helpful in manipulating and analyzing arrays and getting useful results out of them.

With these methods, we can do the searching, sorting on arrays’ elements, filling an array with a particular value, comparing arrays, etc. We will discuss some important methods of Java Arrays class:

Methods of Java Array Class

Java Array methods

1. int compare(array1, array2)

This method compares two arrays in lexicographic order. We pass two arrays as parameters to its methods. It returns 1 if array1 is greater than array2, -1 if array1 is smaller than array2, and a 0 if both arrays are equal to each other.

Code to illustrate the compare() method:

package com.techvidvan.javaarrays;
import java.util.Arrays;
public class CompareMethod
{
  public static void main(String[] args)
  {

    // Create the first Array
    int myArray1[] = { 10, 15, 32, 30 };

    // Create the second Array
    int myArray2[] = { 10, 25, 22 ,30};

    // comparing both arrays
    System.out.println("Comparing two integer arrays: "
        + Arrays.compare(myArray1, myArray2));
  }
}

Output:

Comparing two integer arrays: -1

2. void fill(originalArray, value)

This method is used to fill the specific value to each element of the specified array with a specific type. This method can also be used with all the other primitive data types (byte, short, int, etc.).

Code to illustrate the fill() method:

package com.techvidvan.javaarrays;
import java.util.Arrays;
public class FillMethod
{
  public static void main(String[] args)
  {
    // Create the Array
    int myArray1[] = new int[5];

    int fillvalue = 15;

    Arrays.fill(myArray1, fillvalue);

    // To fill the arrays
    System.out.println("Integer Array on filling: "
        + Arrays.toString(myArray1));
  }
}

Output:

Integer Array on filling: [ 15,15,15,15,15 ]

3. boolean equals(array1, array2)

This method checks whether both the arrays are equal or not and gives the result either as true or false.

Code to illustrate the equals() method:

package com.techvidvan.javaarrays;
import java.util.Arrays;
public class EqualsMethod
{
  public static void main(String[] args)
  {
    //create arrays to be compared
    int array1[] = { 45, 68, 34, 20, 56 };
    int array2[] = { 45, 68, 34, 20, 56 };
    int array3[] = { 55, 78, 44, 10, 56 };

    System.out.println("Comparing array1 and array2: "
    + Arrays.equals(array1,array2));
    System.out.println("Comparing array2 and array3: "
    + Arrays.equals(array2,array3));
  }
}

Output:

Comparing array1 and array2: true
Comparing array2 and array3: false

4. int binarySearch(array [], value)

With the help of this method, we can find or search a specified value inside an array which is given as the first argument. As a result, this method returns the index of the element in the array. The array must be sorted for this search. If the element is not found, it returns a negative value.

Code to illustrate the binarySearch() method:

package com.techvidvan.javaarrays;
import java.util.Arrays;
public class BinarySearch
{
  public static void main(String[] args)
  {
    //create arrays
    int array1[] = { 20, 34,56,78,97 };
    int intKey = 56;
    System.out.println(intKey + " found at index = " + Arrays .binarySearch(array1, intKey));
    System.out.println(20 + " found at index = " + Arrays .binarySearch(array1, 20));
  }
}

Output:

56 found at index = 2
20 found at index = 0

5. copyOf(originalArray, newLength)

We can copy the specified array to a new array with a specified length. The left spaces are assigned to default values in the new array.

Code to illustrate the copyOf() method:

package com.techvidvan.javaarrays;
import java.util.Arrays;
public class CopyOfMethod
{
  public static void main(String[] args)
  {
    //create arrays
    int array1[] = { 65, 20, 34, 56, 78, 97 };

    // To print the elements in one line
    System.out.println("Integer Array: "+ Arrays.toString(array1));

    System.out.println("\nNew Arrays by copyOf method:");
    System.out.println("Integer Array: "+ Arrays.toString( Arrays.copyOf(array1, 10)));
  }
}

Output:

Integer Array: [65, 20, 34, 56, 78, 97]New Arrays by copyOf method:
Integer Array: [65, 20, 34, 56, 78, 97, 0, 0, 0, 0]

Summary

Arrays are important when we need to store multiple values of the same type. They save time and memory required to store a large amount of data. In this tutorial, we covered each aspect of Java Arrays.

We learned the two types of arrays with their declaration and initialization. We also learned how to access an array and also how to pass an array to a method.

After reading this article, you will be able to clone one dimensional or multi-dimensional arrays. Along with this, we covered the Java Array class with its different static methods. This will surely help you to strengthen your concepts in arrays and write complex codes in Java.

Thank you for reading our article. Don’t forget to share your thoughts on this through the comment box below.

Did we exceed your expectations?
If Yes, share your valuable feedback on Google | Facebook


1 Response

  1. Meghana Shandilya says:

    int compare(array1, array2) – This is not working I tried Arrays.compare(array1, array2)

Leave a Reply

Your email address will not be published. Required fields are marked *