Array means collection. In Java also, an array is a collection of similar things. eg.- an array of int will contain only integers, an array of double will contain only doubles, etc.

## Why array?

Suppose you want to store the marks of 100 students. Obviously, you need a better approach over defining 100 different variables and using them. Here the role of array comes in.

## Declaration of array

**int[] z = new int[10];**

It looks similar to defining a variable and actually it is. Here we are declaring 10 variables at one go.

Let's understand this

**int[] z** is representing that '**z**' is an **array** of **type integer** ( as **[ ]** represents array ) and '**new int[10]**' is representing that is it an **array of 10 integers**. In other words, we can say that 'z' is a collection of 10 integers.

Now, a question comes to mind, how to use these 10 variables?

The pictorial view is like this.

Each array has some array elements. In the above array example, there are 10 array elements.

0,1,2....8,9 are indices. It is like, these are the identities of 10 different array elements. Index starts from 0. So, the first element of the array has index 0, the second element has index 1 and so on.

element | 2 | 3 | 15 | 8 | 48 | 13 |

index | 0 | 1 | 2 | 3 | 4 | 5 |

Normally, we declare and assign a value to a variable as follows.

int x;

x = 50;

For an array, we do the same as follows.

int[] z = new int[10];

z[0] = 50;

**int[] z = new int[10]; -** This line will make an array of 10 integers.

**z[0] = 50; -** z[0] represents the first element of the array 'z' and a value of 50 is assigned to it. So, the first element (z[0]) of the array has value 50.

z[0],z[1]....,z[9] are similar to variables we have used before. So, to access an element of an array, we write its index in brackets '[ ]' after the array name i.e. **array_name[index]**.

Thus, for the above example, z[0] is the first element of the array 'z', z[1] is the second element and so z[9] is the tenth element.

And z[0], z[1], ... , z[9] are now same as the variables we have already used.

#### One more declaration

If we know the elements of an array, then we can also declare the array and assign values to the its variables as:

int[] x = {23,32,43,12,43};

Here, we have declared 'x' with its elements. 'x' will automatically become an array of 5 elements as there are 5 elements in 'x'.

The value of the first element (x[0]) of the array is 23, that of the second element (x[1]) is 32 and thus the value of the fifth element (x[4]) is 43.

```
class A0{
public static void main(String[] args){
int[] z = new int[10];
z[0] = 223;
z[1] = 23;
int[] x = {23,32,43,12,43};
System.out.println(z[0]);
System.out.println(z[1]);
System.out.println(x[3]);
System.out.println(x[0]);
}
}
```

23

12

23

Now see this example:

```
import java.util.*;
class A1{
public static void main(String[] args){
int[] z = new int[10];
Scanner s = new Scanner(System.in);
System.out.println("Enter 10 integers of array");
for (int i=0;i<10;i++){
z[i] = s.nextInt();
}
System.out.println("You have entered");
for (int i=0;i<10;i++){
System.out.println(z[i]);
}
}
}
```

11

2

34

2

4

54

96

54

80

44

You have entered:

11

2

34

2

4

54

96

54

80

44

The above example is given to make you understand how to use an array.

There are two for loops in the above example. In the first for loop, we are taking the values of the different elements of the array from user one by one. In the second for loop, we are printing the values of the elements of the array.

Going in the first for loop. In the first iteration, the value of 'i' is 0, so 'z[i]' is 'z[0]'.Thus by writing **z[i] = s.nextInt()**, z[0] will be given its value input by the user. Similary in the second iteration, the value of 'i' will be 1 and 'z[i]' will be 'z[1]'. So, 'z[i] = s.nextInt()' will be used to input value from the user for z[1] and so on. 'i' will go up to 9, so the indices of the array will be ( 0,1,2,...,9).

The second for loop is for printing the values of the different elements. It will work in the same way as the first for loop.

Java has a **predefined function** to get the **length of an array** ( number of elements in an array ).

Let's see an example of this function.

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

So, '**length**' is a function in Java which gives you the **size of an array** ( as shown above ).

#### Let's write our own method to calculate the sum of all the elements of an array:

```
class A3{
public static int cal_sum(int[] a){
int sum = 0;
for (int i=0;i<a.length;i++){
sum = sum+a[i];
}
return sum;
}
public static void main(String[] args){
int[] x = {23,32,43,12,43};
System.out.println(cal_sum(x));
}
}
```

The above example is to show you how we can pass an array in a method. All the other parts are hopefully clear to you.

We called the method 'cal_sum' by **passing the name of the array 'x'** as its argument.

While declaring the method **public static int cal_sum(int[] a)**, __(int[] a)__ represents that this method requires an array of integer to be passed while calling this method.

So, by calling **cal_sum(x)**, we have passed the **array x** to the function **cal_sum**. In the function **public static int cal_sum(int[] a)**, this **a** will become **x** ( as we have passed x ) and further things will proceed.

**a.length** will give the length of the array. So, for an array of 5 elements, it will give 5. So, **i** in for loop must go till 4 only ( i < a.length ).

## For-each loop

There is a new form of for loop. There is no official name to this for loop, but the term for-each is used most often. It is used to iterate over an array. Let's see an example of this.

```
class A31{
public static void main(String[] args){
int[] ar = {1,2,3,4,5,6,7,8,9,10};
for (int m : ar){
System.out.println(m);
}
}
}
```

2

3

4

5

6

7

8

9

10

This is very simple. Here, the variable m will go to every element of the array ar and will take its value.

So, in the first iteration, m is the 1^{st} element of the array ar i.e. 1.

In the second iteration, it is the 2^{nd} element i.e. 2 and so on. Just focus on the syntax of this for loop, rest of the part is very easy.

## 2D Arrays

Same as one-dimensional, we also have 2-dimensional array.

2-dimensional arrays are generally known as **matrix**. These consist of rows and columns.

Before going into its application, let's first see how to declare and assign values to a 2 D array.

### Declaration of 2 D Array

We define 2-dimensional array as follows.

int[][] a = new int[2][4];

Here, **a** is a 2-D array of type int which consists of **2 rows** and **4 columns**.

Column 0 | Column 1 | Column 2 | Column 3 | |
---|---|---|---|---|

Row 0 | a[0][0] | a[0][1] | a[0][2] | a[0][3] |

Row 1 | a[1][0] | a[1][1] | a[1][2] | a[1][3] |

Now let's assign values to the elements of the 2-dimensional array.

### Initialization of 2 D Array

We can assign values to a 2-dimensional array in two ways, same as we do in a one-dimensional array.

In the first method, just assign a value to the elements of the array.

Suppose we declared a 2-dimensional array a[2][2]. After declaring it, we assign a value to its elements.

int[][] a = new int[2][2];

a[0][0]=1;

a[0][1]=2;

a[1][0]=3;

a[1][1]=4;

The second way is to declare and assign values at the same time where each inner curly bracket represents one row.

int a[2][3] = {

{1, 2, 3},

{4, 5, 6 }

};

Here, the value of a[0][0] is 1, a[0][1] is 2, a[0][2] is 3, a[1][0] is 4, a[1][1] is 5 and a[1][2] is 6.

**int[][] s = new int[2][2];** /* valid */

**int[][] s = new int[2][];** /* valid */

**int[][] s = new int[][2];** /* invalid */

**int[][] s = new int[][];** /* invalid */

### Use of 2 D Array

Suppose there are 3 students and both the students are studying 2 subjects (subject 1 and subject 2). We want to display the marks of both the students in the two subjects which we will be taking from the user.

```
import java.util.Scanner;
class A4{
public static void main(String[] args){
float[][] s = new float[3][2];
Scanner s1 = new Scanner(System.in);
for(int i = 0; i < 3; i++)
{
System.out.println("Enter marks of student : "+(i+1));
for(int j = 0; j < 2; j++)
{
System.out.println("Subject : "+(j+1));
s[i][j] = s1.nextFloat();
}
}
for(int i = 0; i < 3; i++)
{
System.out.println("Student" + (i+1));
for(int j = 0; j < 2; j++)
{
System.out.println("Subject" + (j+1) + ":" + s[i][j]);
}
}
}
}
```

Subject : 1

10

Subject : 2

20

Enter marks of student : 2

Subject : 1

30

Subject : 2

10

Enter marks of student : 3

Subject : 1

20

Subject : 2

40

Student1

Subject1:10.0

Subject2:20.0

Student2

Subject1:30.0

Subject2:10.0

Student3

Subject1:20.0

Subject2:40.0

In the above example, firstly we defined our array consisting of 3 rows and 2 columns as **float[][] s = new float[3][2];**

Here. the elements of the array will contain the marks of the 3 students in the 2 subjects as follows.

Subject 1 | Subject 2 | |
---|---|---|

Student 1 | 10 | 20 |

Student 2 | 30 | 40 |

Student 3 | 50 | 60 |

In our example, firstly we are taking the value of each element of the array using a for loop inside another for loop.

In the first iteration of the outer for loop, the value of 'i' is 0. With the value of 'i' as 0, when the inner for loop first iterates, the value of 'j' becomes zero and so s[i][j] becomes s[0][0]. By writing **s[i][j] = s1.nextFloat;**, we are taking the value of s[0][0].

After that, the inner for loop again iterates and the value of 'j' becomes 1. s[i][j] becomes s[0][1] and its value is taken from the user.

Then, the outer loop iterates for the second time and the value of 'i' becomes 1 and the whole process continues.

After assigning the values to the elements of the array, we are printing the values of the elements of the array in the same way using another for loop inside this loop.

Let's see one more example of 2 D Array

Suppose there are 2 factories and each of these factories produces items of 4 different types, like some items of type 1, some items of type 2 and so on. We have to calculate the total product of each factory i.e. sum of the items of each type that a factory produces.

```
class A5{
public static void main(String[] args){
int[][] s = new int[2][4];
s[0][0] = 2;
s[0][1] = 5;
s[0][2] = 7;
s[0][3] = 4;
s[1][0] = 9;
s[1][1] = 3;
s[1][2] = 2;
s[1][3] = 8;
System.out.println("Sum of the items produced in the first factory :");
int sum1 = 0, sum2 = 0;
for(int i = 0; i < 4; i++)
{
sum1 += s[0][i];
}
System.out.println(sum1);
System.out.println("Sum of the items produced in the second factory :");
for(int j = 0; j < 4; j++)
{
sum2 += s[1][j];
}
System.out.println(sum2);
}
}
```

18

Sum of the items produced in the second factory :

22

Here, **s[0][i]** represents the number of items of the first factory and type i, where i takes value from 0 to 3 using for loop and **s[1][i]** represents the nunmber of items of second factory of type i. E.g. - s[0][2] represents the third type of item of first factory and s[1][2] represents the third type of item of second factory. **sum1** is the sum of all the items of factory 1. Similar is the case of the second factory.

So, initially sum1 is 0. Now in the first iteration, s[0][i] is s[0][0]. This means that it will represent the number of the first type of item of the first factory. So, **sum1 += s[0][i]** will become **sum1 += s[0][0]**. Thus, the value of sum1 will be 2. Similarly in the second iteration, s[0][i] will become s[0][1] and will represent the second type of items of the first factory. Now, sum1 will become **2+5** i.e. 7. Similarly, things will go further.

There is no glory in practice but there is no glory without practice.