In this article, we are going to learn about Arrays in Java which is one of the most useful concepts in programming. But, first of all, we are going to learn what are arrays.
What is Array in Java?
If we want to store data, we will need to create a variable. But, what if we want to store a bunch of data, or even more than that?
In this case, we will need to declare many variables, which will store the different data. But, doing this is a tedious task and the programmer needs to remember a lot of variables, assign unique names to variables, etc. To overcome this problem, a concept called array in java is provided. Arrays are the contiguous memory locations that can be used to store data of similar data type.
We can access any element of the array using the index instead of using so many names. This makes our work a lot easier.
Now, we will learn about creating arrays in Java. Creating an array in Java is a bit different compared to C or C++.
For example –
We used the syntax given below to declare an array in C/C++ –
int arr[5];
But, this will give an error in Java. In Java, we can create an array in the similar way we used to create objects. Example –
int[] arr = new int[5];
OR
int arr[] = new int[5];
Array initializing values in Java
We can initialize an array in the following ways –
- int arr[] = new int[] {2,4,6,8,10};
- int arr[] = {2,4,6,8,10};
or, we can initialize the array after declaration too.
public class ArrayExample{ public static void main(String args[]){ int arr[]; arr = new int[3]; arr[0] = 10; arr[1] = 20; arr[2] = 30;} }
In this way, we can initialize an array while declaration or after declaration.
Now, let us see a working program for the use of the concept of the array and taking the values from users.
import java.util.* class Example{ public static void main(String args[]) { int[] arr = new int [5]; Scanner sc = new Scanner(System.in); System.out.println(“Enter 5 numbers”); for(int i=0;i<5;i++){arr[i] = sc.nextInt();} for(int i=0;i<5;i++){System.out.println(arr[i]);} } }
2 – Dimensional Arrays in Java
Two-dimensional arrays are similar to arrays of arrays. We can create a two-dimensional array in Java using any of the two given methods.
- int arr[][] = new int[4][5];
- int [][] arr = new int [4][5];
We will learn more about this from the example given below –
class TwodimensionalArray { public static void main(String[] args) { int[][] a = { {1, 2, 3}, {4, 5, 6, 9}, {7}, }; System.out.println("Length of row 1: " + a[0].length); System.out.println("Length of row 2: " + a[1].length); System.out.println("Length of row 3: " + a[2].length); } }
Output –
Length of row 1: 3 Length of row 2: 4 Length of row 3: 1
Similarly, we can also create arrays having more than two dimensions too.
Try these quizzes: