Java Array Tutorial

Java provides a data structure called an array, which is a fixed-size ordered collection of elements of the same type. Arrays are used to store collections of data, but arrays can also be thought of as collections of variables of the same type.

Declare an array variable (such as: numbers) and use numbers[0], numbers[1]and ..., numbers[99]to represent a single variable, for example number0, number1, ...and number99, instead of declaring each variable separately.

This tutorial explains how to declare array variables, create arrays and access arrays by index.

1. Declare an array variable

To use an array in a program, you need to declare a variable to refer to the array, and specify the array type of the variable. Following is the syntax for declaring an array variable −

Syntax

dataType[] arrayRefVar;   // Recommended method
dataType arrayRefVar[];  // Works, but not the recommended way.
 

Note - Format: dataType [] arrayRefVar is the recommended way. Format: dataType arrayRefVar []From C/C++ language, can be adopted in Java to suit C/C++ programmers.

Java Arrays

 

Example

The following code snippet is an example of this syntax −

double[] myList;   // Recommended method
double myList[];   // Works, but not the recommended way.
 

2. How to Create and Initialize Array in Java?

Arrays can be created using new operators as in the following syntax −

dataType[] arrayRefVar; // Create array arrayRefVar = new dataType[arraySize];

The new keyword is crucial to creating an array. Without using new keyword, we cannot create array reference variables

The above statement does two things −

  • It uses new dataType[arraySize]to create an array.
  • It assigns the reference of the newly created array to the variable arrayRefVar.

Declaring an array variable, creating an array, and assigning a reference of that array to the variable can be done in one statement as follows 

We can Initialize Arrays in Java in two Different ways

 

Initialize using index

dataType[] arrayRefVar = new dataType[arraySize];

Alternatively, an array can be created as follows −

 

Initialize while declaring

dataType[] arrayRefVar = {value0, value1, ..., valuek};
 

Access array elements by index. Array index values ​​start from 0start; that is, they go from 0start to arrayRefVar.length - 1.

Example

An array variable is declared in the following statement myList, which creates an array containing elements 10 of double type and assigns a reference to the array variable to myList

double[] myList = new double[10];
 

3. Working with arrays

for Loops or loops are often used when working with array elements, because all elements in the array are of the same type and the size of the array is known.

Example
Here is a complete example demonstrating how to create, initialize and manipulate arrays

import java.util.*;

public class Test {

    public static void main(String[] args) {
        double[] myList = { 10.01, 12.19, 23.44, 43.95, 77.88, 65.00 };

        
        for (int i = 0; i < myList.length; i++) {
            System.out.print(myList[i] + ", ");
        }
        System.out.println(" ");

       
        double total = 0;
        for (int i = 0; i < myList.length; i++) {
            total += myList[i];
        }
        System.out.println("Sum:" + total);

        
        double max = myList[0];
        for (int i = 1; i < myList.length; i++) {
            if (myList[i] > max)
                max = myList[i];
        }
        System.out.println("Max Element:" + max);
    }
}
 

Output

10.01, 12.19, 23.44, 43.95, 77.88, 65.0,  
Sum:232.47
Max Element:77.88
 

3.1. Java Arrays with foreach loop - Iterate Array items with foreach loop

JDK 1.5 introduced foreach loops or enhanced for loops, which are capable of sequentially traversing an entire array without using an index variable.

example

myList The following code demonstrates how to iterate over all elements in an array

import java.util.*;

public class Test {

    public static void main(String[] args) {
        double[] myList = { 10.01, 12.19, 23.44, 43.95, 77.88, 65.00 };

        // Print all the array elements
        for (double element : myList) {
            System.out.print(element+", ");
        }
    }
}
Output
10.01, 12.19, 23.44, 43.95, 77.88, 65.0,
 

3.2. Passing arrays to methods

Just like passing primitive values ​​to methods, arrays can also be passed to methods. For example, the following printArray()method is used to print intthe elements in an array

import java.util.*;

public class Test {

    public static void main(String[] args) {
        double[] myList = { 10.01, 12.19, 23.44, 43.95, 77.88, 65.00 };

        // Print all the array elements
        printArray(myList);
    }

    public static void printArray(double[] array) {
        for (int i = 0; i < array.length; i++) {
            System.out.print(array[i] + " ");
        }
    }
}
 

Output:

10.01 12.19 23.44 43.95 77.88 65.0
 

3.3. Returning an array from a method

method can return an array. For example, the following method returns an array that is the inverse of the given argument array −

import java.util.*;

public class Test {

    public static void main(String[] args) {
        double[] myList = { 10.01, 12.19, 23.44, 43.95, 77.88, 65.00 };

        // Print all the array elements
        printArray(myList);
        printArray(reverse(myList));
    }

    public static void printArray(double[] array) {
        for (int i = 0; i < array.length; i++) {
            System.out.print(array[i] + " ");
        }
        System.out.println(" ");
    }

    public static double[] reverse(double[] list) {
        double[] result = new double[list.length];

        for (int i = 0, j = result.length - 1; i < list.length; i++, j--) {
            result[j] = list[i];
        }
        return result;
    }
}
Output
10.01 12.19 23.44 43.95 77.88 65.0  
65.0 77.88 43.95 23.44 12.19 10.01

 

3.4. Arrays class

java.util.Arrays The class contains various static methods for sorting and searching arrays, comparing arrays and filling array elements. These methods are overloaded for all primitive types.

serial number method describe
1 public static int binarySearch(Object[] a, Object key) Searches the specified Object (Byte, Int, double, etc.) array for the specified value using the binary search algorithm. The array must be sorted before making this call. If the search key is contained in the list, it returns the index of the search key; otherwise, it returns (-(insertion point + 1)).
2 public static boolean equals(long[] a, long[] a2) Returns if the two specified long arrays are equal true. Two arrays are considered equal if they contain the same number of elements, and all corresponding pairs of elements in the two arrays are equal. Returns if the two arrays are equal true. All other primitive data types (Byte, Short, Int, etc.) can use the same method.
3 public static void fill(int[] a, int val) Assigns the specified intvalue to inteach element of the specified array. All other primitive data types (Byte, Short, Int, etc.) can use the same method.
4 public static void sort(Object[] a) Sorts the specified array of objects in ascending order according to the natural order of the elements. All other primitive data types (Byte, Short, Int, etc.) can use the same method.

 

 

4. Types of Array in Java

In Java, there are two types of arrays:

  1. Single-Dimensional Array
  2. Multi-Dimensional Array

1. Single Dimensional Array

An array that has  one dimension is known as a single-dimensional array. It is just a list of the same data type variables.

Java One Dimension Array

One dimension array can be look like below

int students[] = {56, 98, 77, 89, 99}; 

 

2. Multi-Dimensional Array

 

A multi-dimensional array is just an array of arrays that represents multiple rows and columns. These arrays include 2D, 3D, and nD types. 2D data like tables and matrices can be represented using this type of array

Syntax for Multi Dimensional Array

int students[][] = new int[2][3];

The items in aboe multi dimensional array will be like below

77,68,87
78,56,70

 

 

5. Arrays with Object type

Some times we may require to store multiple type values into single variable. An array of Objects is used to store a fixed-size sequential collection of elements of the same type. For example in a class there are multple students who have different name, rno and marks. So how we can put them into single variable.

Let create a Student class

class Student {
  Student(int rno, String name, int marks) {
    System.out.println("Student rollno is "+ rno+ ", name is "+ name+" and marks is "+marks );
  }
}
Now create Students array and add the student details like below
Student studentObj[] = new Student[3];
studentObj[0] = new Student(1,"Ram", 98);
    studentObj[1] = new Student(2,"Ravan",96);
    studentObj[2] = new Student(3,"Hanuman", 99);

 

 

6. Advantages and Disadvantages of Arrays in Java

Advantages

  • We can access an array element value randomly just by using the index indicated by the array.
  • At a time, we can store lots of values in arrays.
  • It becomes easier to create and work with the multi-dimensional arrays.

Disadvantages

  • Arrays in Java do not have in-built remove or add methods.
  • In Java arrays, we need to specify the size of the array. So there might be a change of memory wastage. So, it is recommended to use ArrayList.
  • Arrays in Java are strongly typed