In this article you will learn about arrays in Java through simple beginner friendly examples.

What Are Arrays?

Arrays allow for the storage and retrieval of an arbitrary quantity of values. They are analogous to vectors in mathematics.

Arrays of arrays are analogous to matrices, and act as multidimensional arrays. Arrays can store any data of any type: primitives such as int or reference types such as Object.

How to declare an Array

Declare an array using the following syntax:

   ArrayType[] myArray;

Another valid syntax (less commonly used and discouraged):

 ArrayType myArray[];

To declare a multi-dimensional or jagged arrays:

 ArrayType[][][] myArray;

More Array HowTo’s

Accessing (reading) element at index:

  ArrayType myVar = myArray[index];

Assign value to position index of array:

 myArray[index] = value;

To initialize an array:

 ArrayType[] myArray = new ArrayType[arrayLength];

Array initialization syntax with values provided:

 int[] ints = {1, 2, 3};

Multi-dimensional array initialization. int[] extends Object (and so does anyType[]) so null is a valid value.

 int[][] ints = {{1, 2}, {3}, null};

How to Compare Two Arrays

The example below allows you compare array's either by their references or contents.

Step 1: Getting Started

Create Java file then Import array from the java.util package:

 import java.util.Arrays;

Step 2: Add the following code

Here's the full code:

 import java.util.Arrays;

/**
 * Example of how to compare array references as well as contents
 */
public class ArrayEqualsExample {
    public static void main(String[] args) {
        int []arr1=new int[30];
        int []arr2=new int[30];
        //Compares references
        System.out.println("References: "+arr1.equals(arr2));
        //Compares contents
        System.out.println("Contents: "+Arrays.equals(arr1,arr2));
    }
}

Step 3: Run

Run the project:

 $javac ArrayEqualsExample.java

You will get the following:

References: false
Contents: true

Conclusion

If you compare the two arrays, their references are different while their contents are the same.

How to create and Iterate a 2D Array

A 2D array is also called a multidimensional array. This example will teach you how to iterate it and retrieve it's contents.

Step 1: Create Java

Create a file with .java extension called Array2DExample.java or any name you wish.

Step 2: Write Code

Add the following code:

 /**
 * Example of how tocreate and iterate a 2D array
 * 
 */
public class Array2DExample {
    public static void main(String[] args) {
        int [][]arr=new int[5][5];
        int count=0;
        for(int i=0;i<5;i++){
            for(int j=0;j<5;j++){
                arr[i][j]=count++;
            }
        }

        for(int i=0;i<5;i++){
            for(int j=0;j<5;j++){
                System.out.println(arr[i][j]);
            }
        }
    }
}

Run

Run using the javac command:

$javac Array2DExample.java

Here's what you will get:

 0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

Conclusion

We've seen how to create a multidimensional array containing integers, then looping through it to print out those numbers.

How to convert an Array to a List

Sometimes you want to use a list as it has more ready made methods rather than an array. This example shows you how to do that. Basically to do the conversion you use the asList() method.

Step 1: Create java file

Create a java file.

Step 2: Write Code

Add the following code to the file:

 import java.util.Arrays;
import java.util.List;

/**
 * How to Convert Array to List
 */
public class ArraysToList {
    public static void main(String[] args) {

        String[] str=new String[]{"Casini","Voyager","Messenger","Galileo","Kepler","WMAP","Pioneer","Mars Express"};
        List s=Arrays.asList(str);
        s.forEach(System.out::println);
    }
}

Step 3: Run

You can run the project using the javac command if you are using the commandline:

 $javac ArraysToList.java

You will get the following:

Casini
Voyager
Messenger
Galileo
Kepler
WMAP
Pioneer
Mars Express

Conclusion

To convert an array to a list all you need do is use the asList() method.

How to Get Average of Values in an array using stream

This example explores how you can get the average value of an array of integers. An average is basically the total sum of a group of numbers divided the number of individual items in that group. It can also be called the mean value.

Step 1: Create Java

Create a .java file.

Step 2: Write code

Add the following code:

 import java.util.Arrays;

/**
 * Average using Streamm
 */
public class AveragesExample {
    public static void main(String[] args) {
         Arrays.stream(new int []{2,4,6,8,10}).average().ifPresent(System.out::println);
    }
}

Step 3: Run

Run the code:

$javac AveragesExample.java

Result:

6.0

Categorized in: