Data Structures in Java — Arrays

Nickson Joram
Analytics Vidhya
Published in
11 min readApr 30, 2020

We have seen Data Structure (a finite way to store and organize data so that it can be used efficiently), available Data Structures, and built-in classes and interfaces to handle Data Structures earlier in this article.

Here, you will be able to know further about one of the most popular data structures that is being used in almost every programming language, Array.

Let me make sure that you are familiar with the two words.

  1. Variable (or scalar)
  2. Data type

But why? When handling the array, we must be aware of these wordings. Why if not? Well, in a while, with the flow of this article, you will get your answer. Variable is a storage address in collaboration with an associated symbolic name. In Mathematics, when we were solving things in Algebra, for unknown terms, we have used the lowercase alphabet (like, let x be…). Check the following variables.

  1. x = 35
  2. y = bob
  3. z = true

Are these three variables are similar? NO!

To justify the answer (or to clarify), look at the picture below.

You can see a lot of eatable things. Aren’t they? Are they all same? How do you purchase them? Asking for anything or asking specifically? When we are asking specifically, we are just handling them as groups. We are selecting from the groups in which we have already separated them. How to define the groups then? We can group them as fruits and vegetables. What else?

Now, you can see a number of groups in which the above fruits and vegetables are separated into independent groups. So, even though they all are eatable, they all are not the same. Also, on your right, you have fruits and on your left, you have vegetables. Now see our previous example.

Variables x, y, and z are not similar. Because x is assigned with a positive number (integer), y is assigned with a text (String), and z is assigned with a Boolean value. This difference is because of different Data types. I’m not going to discuss it further and I hope you have a clear idea about these now.

So, how these things are affecting the topic, Array? What is Array? Simply, Array is a predefined variable with a data type that can hold a fixed number of values, altogether but in separate locations. This explains, the array members should be in the same data type. We also can treat arrays as sets, well-defined sets. It has a pre-defined data type, cardinality, and elements (these concepts have been discussed below). So, when handling the arrays, you must be aware of the terms variable and data type.

Can you have some onion inside the bag of fruits? Practically, you can have, but then can you call the bag a bag of fruits? Here, the bag of fruits is the array name and fruits are the members inside the array. We call those members as elements as we do in sets. You can have either one of each fruit available or whatever the number in each fruit. When the number of one fruit increases, then we can refer to it as duplicate fruit. So in an array, if we have a repeating element, we can call it a duplicate element.

We can divide the array types into 3 categories.

  1. One dimensional array (Vector array)
  2. Two-dimensional array
  3. Multidimensional array

One dimensional array (Vector array)

We have been using arrays since we write the Hello World program in Java. Can you recall the codes to see whether is it true or false?

public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World!");
}
}

There in the main method, we have something called String [ ] args. Have you ever thought about it? What does it mean? Well, you may get the answer in a while.

In Java, we can either create an array with specified size or we can create an array with its elements like this.

(data type) [] variable name = new (data type)[length];

Here, data type should be given (String, int, char …) with array name (variable name) as defined. And in length, we have to give a positive integer value to define how many of elements that we are going to include. Simply, the cardinality of our set. So the array initialization shall be done like this.

int [] myNumbers = new int [5];

An array with array name myNumber of integer type (going to host integer values) has been created with size 5. ie; we can have 5 integers inside a single variable myArray. We can divide the items like this.

int [] myNumbers;
myNumbers = new int[5];

In the first line, we are just initializing an array in Integer type with the variable name myNumbers. In the next line, we are allocating the memory for the initialized array. But why? We can do it in a single line. Isn’t it?

Some experts prefer to initialize every variable at the top of their classes and will access it inside the classes. When you have to solve something in-order to get the idea of memory needed fr an array, you can simply use this method of handling the memory allocation.

Simply,

int [] myNumbers;
/*{
size = input1 + output1 from another function;
}*/
myNumbers = new int[size];

Here the size of the array varies with the input and output from another function. In these types of cases, we can use the initialization and memory allocation separately.

We can create an array like this too as mentioned above.

(data type) [] variable name = {elemet1 of data type, elemet2 of data type, elemet13 of data type, elemet4 of data type, …..};

That is;

int [] myNumbers = {5, 6, 7, 8, 9};

So, if we are planning to host an array with 10 String values (say names of 10 friends), how can we initiate the array?

String [] names = new String [10];

In a similar manner, you can create arrays as you needed as follows. You can have primitive and non-primitive or objects in an Array.

int intArray[]; //or int[] intArray; both ways are correct
byte byteArray[];
short shortsArray[];
boolean booleanArray[];
long longArray[];
float floatArray[];
double doubleArray[];
char charArray[];
Object[] objectArray; //an array of Object
Collection[] collectionArray; //array of Collection of unknown type

What would be in the array when we initialize it with size but not have filled any elements into it? Will it be empty or have any values? It won’t be empty. It will assign the default values. What are they?

//If it is a boolean array : false
//If it is an int array : 0
//If it is a double array : 0.0
//If it is a String array : null
//If it is an User Defined Type array : null

The following is a graphical interpretation of an array.

An Array of size 7

This array has been initiated like this.

int [] myArray = {3, 8, 1, 0, 5, -2, 32};

Here, you can see a new term called Indices (plural form of the index). What is an index, generally? Pointing object isn’t it? Here, in the array, we can access each and every element in any way we want. For that, we use indices. There, in the picture, you can see the first element in our array (3) is at the index of 0. This array begins at index 0 and goes up-to index 6, thus the size is 7 and the index range is [0, 6]. We can access the elements at any index (but within the index range). How to access the element at a particular index?

int value = myArray[n]; //Where 0<= n <=6

If n=4, then what will be assigned to value? 4th element or 5th element?

int value = myArray[4];
//value = 5 which is the 5th element. 1st element is at 0th position

How to print 4th element then? It is like a normal print statement can be carried out like this.

System.out.println("The 4th element of myArray is " + myArray[3]);
//The 4th element of myArray is 0

If you are asked to add 10 with each element of myArray, what will you do? and how?

myArray[0] = myArray[0] + 10;
.
.
.
myArray[6] = myArray[6] + 10;

What if this array size is 20? 50? 100? Will you add like this? This question is not only for adding but for every action that may be assigned for the entire array of elements. That is why we have control structures, especially, for loops.

So, the above task shall be done using for loop like this.

for(int i = 0; i<7; i++){
myArray[i] = myArray[i] + 10;
}

If the array size is dependent on any other operations, in that case, we can’t be able to judge the size and include it in the for loop. So we can use the for loop like this.

for(int i = 0; i<myArray.length; i++){
myArray[0] = myArray[0] + 10;
}

What about filling an array from user inputs? Have you ever tried getting input from the keyboard in your Java classes? Have you heard about Scanner class in Java?

The Scanner class is used to get user inputs, and you can see it in the java.util package. To use the Scanner class, create an object of the class. There are many methods to be used in Scanner class which you can check at the Scanner class documentation.

Look at the following lines of codes and try to understand. I’ve added comments along with the lines, hope it may help you if you can’t understand.

//Object to access Scanner class
Scanner input = new Scanner(System.in);
System.out.println("Enter the size of the array you want to make");
int size = input.nextInt(); //method to get Integer input
int [] numbers = new int [size]; //Integer array initialization
System.out.println("Enter the elements of the array");

for(int i=0; i<size; i++){
numbers[i]=input.nextInt(); //Assigning the array elements(Integer)
}

You can check whether the array you intended to make has been created or not by the following execution.

System.out.println(“Elements are”);
for(int i=0; i<size; i++){
System.out.print(numbers[i]+ “ “); //Printing the elements
}

In this way, you can do whatever the operations in a vector Array using the loops too.

Two-dimensional array

We have seen that the Vector array is just like a single row of chairs.

Vector Array’s structure

What if we have a same number of chairs per row in more than 1 row?

Two-dimensional array’s structure

Yeah, that is how a two-dimensional array looks like. But why the same number of chairs in all rows? What if it has different numbers of chairs per row?

Well, let's see further to know to about this.

Have you ever seen this?

Don’t lie!!

It is a matrix. We have studied these in our secondary schooling, the most probably. Yes? Now, can you understand why there is a same number of chairs in all rows? Simply, we can call two-dimensional array also as a matrix. Don’t think about a different number of chairs per row for now.

Just like we did in vector arrays, we have to define the array size (look at the matrix image). Since it is two-dimensional, there will be two important aspects to decide its size. How do we are counting the total number of chairs in a chair arrangement? By using row count and column count. We are applying the same concept here. So we have to define the size at the initialization as we did in vector arrays.

Initialization of two-dimensional array shall be done like this.

(data type) [ ][ ] variable name = new (data type)[row][column];

For example,

int[][] matrix = new int[4][3]; //number of rows 4 and columns 3

We can also initialize like this

int[][] abc = { { 1, 2, 3 },
{ 4, 5, 6 },
{ 7, 8, 9 },
{ 10, 11, 12}};

How to access the elements in two-dimensional arrays?

Just see the following example.

int[][] A = new int[3][3];

In this image, you can see how the cells have been addressed. The first value is the row, and the next is a column. So in the first column, you can see that the value remains constant and that is 0. Similar way, you can understand the entire index-wise approach in the two-dimensional array.

We have a question already. What if each row has a different number of chairs? But why? Imagine that you are hosting a function and arranging transport for the invitees. You’ve invited unequal numbers of people from 10 different cities. Now, will you arrange buses with the same number of seats or? If you have 50 invitees as maximum from a city and only 1 invitee as least from another city, will you send a 50 seat bus to each city?

That is why we need a special two-dimensional array called jagged arrays.

Jagged arrays

We can’t simply assign sizes in initializing arrays because it takes memory. So, even though we need two-dimensional array, but we are sure that the array length along the rows is not equal, we can use Jagged arrays. Simply, a Jagged array is an array of arrays such that member arrays can be of different sizes. So we can create a two-dimensional array with a variable number of columns in each row.

This is an example of the jagged array. Here you can see that the rows are fixed and the numbers in each row differ.

Initialization of this array can be done like this. First initialization is similar two-dimensional arrays.

int arr[][] = new int[2][]; //two rows

To make this two-dimensional array jagged, we have to define different column lengths for each row.

arr[0] = new int[3]; // 1st row has 2 columnsarr[1] = new int[2]; // 2nd row has 2 columns

The rest of the applications are the same as we saw in vector arrays and two-dimensional arrays.

Multidimensional array

Two-dimensional array is also a multi-dimensional array. We have seen the initialization of a two-dimensional array. Then how it is going it to differ from three-dimensional array? Just like cube or cuboid from square and rectangle, isn’t it?

Initialization can be done like this

int[][][] arr = new int[10][20][30];

or

int[][][] arr = { { { 1, 2 }, { 3, 4 } }, { { 5, 6 }, { 7, 8 } } };

The syntax works like this.

data type [][][] array name = new data type [array index][row index][column index];

I hope, now you have a clear idea about arrays, indices, types of arrays, and the ways to handle them.

The array is the easiest and playable data structure in Java compared to other data structures. So have fun and learn by practicing.

Feel free to ask questions, I’ll be happy to answer them.

--

--