Arrays in Java
-
Last Updated: December 18, 2023
-
By: javahandson
-
Series
In this article, we will learn what is an array and the types of arrays in Java with proper examples. If you want to learn more about other Java, Java 8, or Spring concepts then please check the above menu options.
An array is a collection of elements i.e. an array can store a group of elements into a single variable. Ex. We can store a group of integer elements, String elements or float elements, etc using a single variable.
An array is a homogeneous set of elements which means we can store only one type of values into a single array. We cannot mix up multiple data types into a single variable.
Ex. We cannot store integer and String values in a single variable. We have to create separate arrays to store different data types.
Suppose an organization has 1000 employees and we have to store their employee id’s then we will need 1000 separate variables for storing the employee id’s like below
int employeeId1; int employeeId2; int employeeId3; ... int employeeId1000;
Now to store employee ID values into these variables we will need another 1000 statements. Imagine how hectic a task it will be. Instead, if we can make use of a single variable that can represent all these 1000 variables then it would be very beneficial. Such a variable is known as an array. Array helps us to replace multiple statements with just one or two statements.
Arrays are categorized into 2 parts:
A Single-dimensional array is also known as 1D array. It represents a row or a column of elements. Ex. We can represent all the employee id’s in a 1D array.
int employeeId[] = new int[10]; // employeeId is an array variable name that represents all the 10 employee id's.
There are 2 ways of creating a 1D array:
1. We can declare an array and store the values of elements directly at the time of declaration.
int employeeId[] = {101, 102, 103, 104, 105, 106, 107, 108, 109, 110};
JVM will create 10 blocks of memory to store the above 10 employee IDs. Each memory block can be represented by an index. An array index starts from 0.
If we have to access the first element of an array then we can access that using employeeId[0], the second element of an array using employeeId[1], and the third element of an array using employeeId[2], and so on.
0, 1, 2 … is called an index of the array. Here index represents the position of an element in the array. A 1D array will only have one index.
package com.java.handson.arrays; public class OneDArray { public static void main(String[] args) { int employeeIds[] = {101, 102, 103, 104, 105, 106, 107, 108, 109, 110}; System.out.println("First employee id : "+employeeIds[0]); System.out.println("Second employee id : "+employeeIds[1]); System.out.println("Third employee id : "+employeeIds[2]); System.out.println("Tenth employee id : "+employeeIds[9]); } } Output: First employee id : 101 Second employee id : 102 Third employee id : 103 Tenth employee id : 110
Write a program to print 1D array elements using iteration.
package com.java.handson.arrays; public class OneDArray { public static void main(String[] args) { int employeeIds[] = {101, 102, 103, 104, 105, 106, 107, 108, 109, 110}; for (int i=0; i<employeeIds.length; i++) { System.out.println("Employee id is : "+employeeIds[i]); } } } Output: Employee id is : 101 Employee id is : 102 Employee id is : 103 Employee id is : 104 Employee id is : 105 Employee id is : 106 Employee id is : 107 Employee id is : 108 Employee id is : 109 Employee id is : 110
Note* length is a property of an array that will help us to know the size of the 1D array.
2. We can declare an array and just assign memory to the array using a new operator. We will not assign values to the array at the time of declaration.
int employeeIds[] = new int[10];
Here JVM has assigned 10 memory locations for storing the employee IDs but there are no elements stored in the array yet. If we have to store elements in the array then we can do that using the index like below.
employeeIds[0] = 101; employeeIds[1] = 102; employeeIds[9] = 110;
package com.java.handson.arrays; public class OneDArray { public static void main(String[] args) { int employeeIds[] = new int[10]; employeeIds[0] = 101; employeeIds[1] = 102; employeeIds[9] = 110; System.out.println("First employee id : "+employeeIds[0]); System.out.println("Second employee id : "+employeeIds[1]); System.out.println("Third employee id : "+employeeIds[2]); System.out.println("Tenth employee id : "+employeeIds[9]); } } Output: First employee id : 101 Second employee id : 102 Third employee id : 0 Tenth employee id : 110
In the above example as we have not assigned value to the third element of the array hence it has printed the default value of integer as 0.
In the above approach, we have created a 1D array in one step.
int employeeIds[] = new int[10];
But we can split the above statement into 2 parts i.e. one is declaring an array and the second statement is to instantiate an array.
int employeeIds[]; employeeIds = new int[10];
Write a program to accept input from the keyboard and store those values in an array.
package com.java.handson.arrays; import java.util.Scanner; public class OneDArray { public static void main(String[] args) { int employeeIds[]; employeeIds = new int[5]; Scanner scanner = new Scanner(System.in); System.out.println("Input 5 employee id's from keyboard"); for (int i=0; i<employeeIds.length; i++) { employeeIds[i] = scanner.nextInt(); } System.out.println("Printing all the employee id's in array"); for (int i=0; i<employeeIds.length; i++) { System.out.println("Employee id is : "+employeeIds[i]); } } } Output: Input 5 employee id's from keyboard 101 102 103 104 105 Printing all the employee id's in array Employee id is : 101 Employee id is : 102 Employee id is : 103 Employee id is : 104 Employee id is : 105
When writing a 1D array we can place the square brackets before or after the array name.
int employeeIds[] = {101, 102, 103, 104, 105}; int[] employeeIds = {101, 102, 103, 104, 105}; int []employeeIds = {101, 102, 103, 104, 105}; int employeeIds[] = new int[5]; int[] employeeIds = new int[5]; int []employeeIds = new int[5];
In this article, we will understand 2 dimensional (2D) array. A 2D array represents several rows and columns of data just like a matrix or an Excel sheet. In an Excel sheet or a matrix if we want to identify the location of the data then we should know the row and column numbers.
Let us see an example below where we are creating a 2D array named employees[][].
Age Salary Designation John 40 1000 Engineer Rob 46 1200 Sr.Engineer Anna 51 2000 Manager
Find Anna’s designation
Anna’s information is stored in the 3rd row and her designation is stored in the 3rd column. Hence when combined we get to know the element is stored at employees[2][2] and the result is ‘Manager’.
Note* Since the array index starts from Zero that is the reason the third row and the third column are depicted as [2][2].
There are 2 ways of creating a 2D array:
1. We can declare a 2D array and store the values of elements directly at the time of declaration.
int employeeIds[][] = {{101, 102, 103}, {201, 202, 203}, {301, 302, 303}};
In the above example, there are 3 rows and 3 columns so JVM creates 3*3 = 9 blocks of memory as there are 9 elements stored in the array.
Below we will depict the above array that will help us to understand a 2D array better.
101 102 103 201 202 203 301 302 303
The row and column numbers of the above matrix will be like below
00 01 02 10 11 12 20 21 22 00 = 1st row and 1st column (101) 01 = 1st row and 2nd column (102) 02 = 1st row and 3rd column (103) 10 = 2nd row and 1st column (201) 11 = 2nd row and 2nd column (202) 12 = 2nd row and 3rd column (203) 20 = 3rd row and 1st column (301) 21 = 3rd row and 2nd column (302) 22 = 3rd row and 3rd column (303)
The above 2D array is a combination of three 1D arrays. The first row can be treated as the first 1D array similarly second and third rows can also be treated as 1D arrays. If we have to fetch any element from the above array then we should know the row and column number. So an element, in general, can be written as arrayName[i][j] where i represents the row position and j represents the column position.
Write a program to create a 2D array and fetch a few elements from that array.
package com.java.handson.arrays; public class TwoDArray { public static void main(String[] args) { int employeeIds[][] = {{101, 102, 103}, {201, 202, 203}, {301, 302, 303}}; // The indexing starts from 0 System.out.println("1st row and 3rd column element : "+employeeIds[0][2]); System.out.println("2nd row and 3rd column element : "+employeeIds[1][2]); System.out.println("3rd row and 2nd column element : "+employeeIds[2][1]); } } Output: 1st row and 3rd column element : 103 2nd row and 3rd column element : 203 3rd row and 2nd column element : 302
2. We can declare a 2D array and just assign memory to the array using a new operator. We will not assign values to the array at the time of declaration.
int employeeIds[][] = new int[2][3];
Here JVM has assigned 2*3=6 memory locations for storing the employee IDs but there are no elements stored in the array yet. If we have to store elements in the array then we can do that using the indexes like below.
employeeIds[0][0] = 101; employeeIds[0][1] = 102; employeeIds[1][2] = 203;
We can accept these elements from within the program or we can read them from the keyboard.
Write a program to create a 2D array accept the elements from within the program and print it.
package com.java.handson.arrays; public class TwoDArray { public static void main(String[] args) { int employeeIds[][] = new int[2][3]; employeeIds[0][0] = 101; employeeIds[0][1] = 102; employeeIds[0][2] = 103; employeeIds[1][0] = 201; employeeIds[1][1] = 202; employeeIds[1][2] = 203; // We have to iterate through rows and columns to print the elements // As there are 2 rows for (int i=0; i<2; i++) { // As there are 3 columns for (int j=0; j<3; j++) { System.out.print(employeeIds[i][j] + " "); } System.out.println(); } } } Output: 101 102 103 201 202 203
In the above approach, we have created a 2D array in one step.
int employeeIds[][] = new int[2][3];
But we can split the above statement into 2 parts i.e. one is declaring an array and the second statement is to instantiate an array.
int employeeIds[][]; employeeIds = new int[2][3];
Write a program to create a 2D array accept the elements from the keyboard and print it.
package com.java.handson.arrays; import java.util.Scanner; public class TwoDArray { public static void main(String[] args) { int employeeIds[][]; employeeIds = new int[2][3]; Scanner scanner = new Scanner(System.in); System.out.println("Input 6 elements to store in a 2*3 2D array : "); // As there are 2 rows for (int i=0; i<2; i++) { // As there are 3 columns for (int j=0; j<3; j++) { employeeIds[i][j] = scanner.nextInt(); } } System.out.println("Printing the above 2D array : "); // We have to iterate through rows and columns to print the elements for (int i=0; i<2; i++) { for (int j=0; j<3; j++) { System.out.print(employeeIds[i][j] + " "); } System.out.println(); } } } Output: Input 6 elements to store in a 2*3 2D array : 101 102 103 201 202 203 Printing the above 2D array : 101 102 103 201 202 203
When writing a 2D array we can place the square brackets before or after the array name.
int employeeIds[][] = {{101, 102, 103}, {201, 202, 203}, {301, 302, 303}}; int[][] employeeIds = {{101, 102, 103}, {201, 202, 203}, {301, 302, 303}}; int [][]employeeIds = {{101, 102, 103}, {201, 202, 203}, {301, 302, 303}}; int employeeIds[][] = new int[3][3]; int[][] employeeIds = new int[3][3]; int [][]employeeIds = new int[2][3];
The length is a property of an array. In a 1D array, it tells us the size of an array but in the case of a 2D or 3D array, it gives us the number of the rows of the array. If we have to find the number of columns in a row then we have to fetch the row and call the length property on that row.
package com.java.handson.arrays; public class LengthProperty { public static void main(String[] args) { int studentIds[] = {501, 502, 503, 504, 505}; System.out.println("Size of 1D array : "+studentIds.length); int employeeIds[][] = {{101, 102, 103}, {201, 202, 203}}; System.out.println("No. of rows of 2D array : "+employeeIds.length); System.out.println("No. of columns in first row of 2D array : "+employeeIds[0].length); System.out.println("No. of columns in second row of 2D array : "+employeeIds[1].length); } } Output: Size of 1D array : 5 No. of rows of 2D array : 2 No. of columns in first row of 2D array : 3 No. of columns in second row of 2D array : 3
So this is all about what is an array and the types of arrays in Java with proper examples. If you have any questions on this topic please raise them in the comments section. If you liked this article then please share this post with your friends and colleagues so that they can learn Java and its frameworks in more depth.