Java Arrays



This article will cover the use of Arrays in Java.

What are Arrays?

In programming, an Array is a data structure which can store a fixed number of elements of the same data type within it. But where do we use Arrays in Java? Let’s say we wanted to store 1000 values. It would incredibly slow and inefficient to create a 1000 different variables to store the data.

Hence, we use Arrays, where we can store an almost infinite number of values within it. You may think of an Array as a collection of variables bound together by a common name.

Java allows for multi dimensional Arrays to be created, not just one dimensional. Although, one dimensional arrays are the most common.


One Dimensional Arrays

The general form of a one dimensional array is as follows.

type array_name[] = new type[size];

The type defines that data type of the elements being stored in the Array. Remember, the array type and element type should be the same. The size defines the size of the Array, or in simpler words, the number of elements the Array can hold.

The above process is actually a two step process. In the first step the Array is initialized, with a data type. In the second step, we assign the array some memory space. You choose to first initialize the array, and assign it memory in a later step, as shown below.

type array_name[];
// Instructions
.
.
.
array_name = new type[size];

Creating a one dimensional Array

The below code will create a Array called "Example" of size 10 that stores integers.

int example[] = new int[10];

The next step is store some values into this Array. Currently, the values are set to null. The following code runs a for loop that runs from 0 to 10, storing values in the Array with each iteration.

import java.util.Arrays;

for (int x = 0; x != 10; x++) {
   example[x] = x;		
}

Now to actually print out the Array to check it’s value. You can’t use the regular println() function here. toString is a function from the Java Arrays library that is designed to print out the values in an Array.

//Printing the whole Array
System.out.println(Arrays.toString(example));
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Iterating over the Array

When working with the values of a Arrays, the best way to utilize them is iterating over the Array. Iterating allows you access each value in the Array individually, giving you greater control and more options.

One thing to remember, is that indexing in Java begins from 0. This means that the first position in the Array is not example[1], rather it is example[0]. Hence, in the example below, we begin from iterating from position 0.

public class Arrayexample {
	public static void main(String[] args) {
		int example[] = new int[10];
		
                //Storing values
		for (int x = 0; x != 10; x++) {
			example[x] = x;		
		}
		
                //Iterating over values
		for(int x = 0; x != 10; x++) {
			System.out.println(example[x]);
		}
	}
}

0
1
2
3
4
5
6
7
8
9

We can use the println function here since we’re just using it print single values. Only use the toString() function to print out entire Arrays.


Multi-Dimensional Arrays

Multi dimensional arrays are basically arrays within arrays. In terms of variables ,a multi dimensional array is a collection of variables, and these variables themselves are collections of variables. And since Java Arrays are known as collections of variables, a multi dimensional array is a collection of arrays.

We’ll be working with two dimensional Arrays for this section, but the concept remains the same for 3 dimensional arrays and above. The general form for a 2-D array is shown below.

type array_name[][] = new type[size1[[size2] 

Creating a two dimensional Array

The below code creates a two dimensional Array with the name example of type int. Setting the sizes to 3 and 5 respectively, creates 3 Arrays, each holding 5 values, stored in the Array called example.

int example[][] = new int[3][5];

If you want to know the maximum number of elements an array can store, multiply all it’s sizes. For a three dimensional array for instance, 3 * 8 * 10 = 240 values.

Iterating over the array

Iterating through multi dimensional arrays is a bit more complicated than iterating through one dimensional Arrays. The purpose of iterating is to pass through each value in the Array. Hence, we need to setup multiple for loops. Using a single for loop will only iterate through the one dimensional arrays within the 2-D array, not the values possessed by the one dimensional arrays.

import java.util.Arrays;

public class Arrayexample {
	public static void main(String[] args) {
		//Creating the Array
		int example[][] = new int[3][5];

                // Iterating using single for loop
		for (int x = 0; x != 3; x++) {
			System.out.println(Arrays.toString(example[x]));
		}
	}
}

[0, 0, 0, 0, 0]
[0, 0, 0, 0, 0]
[0, 0, 0, 0, 0]

As you can see, we received three one dimensional Arrays as output. Now we’ll try using two for loops instead.

public class Arrayexample {
	public static void main(String[] args) {
		//Creating the Array		
		int example[][] = new int[3][5];

                // Iterating using two for loops
		for (int x = 0; x != 3; x++) {
			for (int y = 0; y != 5; y++) {
			     System.out.println(example[x][y]);
			}
		}
	}
}
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0

Using this concept, we can store values within the 2 Dimensional array as well.

Printing a multi Dimensional Array

The regular toString function wont work for a multi dimensional Array. Instead, we have to use another function the Java Arrays Library called deepToString. “Deep” refers to it’s ability to be able print out more than just the surface layer of a multi dimensional array.

//Importing library
import java.util.Arrays;

// Creating the array
int example[][] = new int[3][5];

//Storing values
for (int x = 0; x != 3; x++) {
    for (int y = 0; y != 5; y++) {
         example[x][y] = 1;
    }
}	

System.out.print(Arrays.deepToString(example));
[[1, 1, 1, 1, 1], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1]]

Length of an Array

Up to this point we’ve only created Arrays of sizes we were aware of. Because of this, we were able to place appropriate values in the for loops while iterating over them or storing values. But what if you didn’t know the size of the Array? This is where the .length function comes in.

public class example {
	public static void main(String[] args) {
			
		int example[] = new int[10];
		System.out.println(example.length);
	}
}
10

Multi-dimensional Arrays can a little trickier. If you simple use the technique above on a 2-D Array, it will only give you the number of 1-D Arrays in it. To find the number of values each 1-D array holds you’ll have to use example[0].length instead of example.length.


This marks the end of the Java Arrays article. Any suggestions or contributions for CodersLegacy are more than welcome. You can ask any relevant questions in the comments section below.

Leave a Reply

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