Array is group of variables having same name as well as having same data type.Array in java behaves different from c/c++.Value is stored inside array by it’s index value.There are two different type of array is available in java .First one is single dimensional array and second one is multi dimensional array.Let’s take a look at it’s two different type mainly

1.Single dimensional array
Array having only one dimentional is called as single dimensional array
Syntax

Data_type Var_name[ ];
Var_name=new Data_type[size];

Example

int a[ ];
a=new int[5];

First we have declared a variable having unknown size and then size is defined with using new operator and memory is allocated

Let’s execute program of single dimensional array

Problem– Calculate sum of five integer number using array

Code–>>

class sin{
public static void main(String args[])
{
int a[ ];
a=new int[5];
for(int j=0;j<5;j++)
{
a[j]=j;
}
int result=0;
for(int i=0;i<5;i++)
{
result=result+a[i];
}
System.out.println(“Sum of values =”+result);
}

output–>>

Sum of values= 10

Logic–>>
First we have declared an array variable ‘a’ and defined it’s size with new operator .Now we initialized its five value with using for loop .So first a[o]=0 ,a[1]=1…and so on.
Then we have taken a variable result having integer type and initialized it’s value to zero.Now inside for loop we have written operation to calculate sum.In First iteration result will be 0,in second it become 1,in third it become 3 …and in last it become 10.So it finally prints the result= 10.



2.Multidimensional array-It have two or more dimension having same data type and same name.
Syntax

Data_type Var_name[ ] [ ];
Var_name= new Data_type [size][size];

Example

int a[ ] [ ];
a=new int [3][3];

It have two dimensions and size of two dimensions is generated.

Let’s execute multi-dimensional array program in java

Problem-Execute a java program to print matrix.

Code–>>

class multiple{
public static void main(String args[])
{
int a[][];
a=new int[3][3];
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
a[i][j]=j;
}
}
System.out.println(“Matrix is “);
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
System.out.print(” “+a[i][j]);
}
System.out.println(” “);
}
}
}

Output–>>

0 1 2
0 1 2
0 1 2

Logic–>>


It is easy to print matrix with using multidimensional array .First we have declared variable having two dimension and initialized it’s index with value  using two for loop statement.When i is equal to zero it goes inside the loop and execute the statement until j become 3.So  it have a[0][0]=0,a[0][1]=1 and a[0][2]=2. Similarly we can do it for i=1 and i=2.After initializing its value to particular index,we will do same process for printing it into matrix form.Note that we used print instead of println inside the for  loop with j variable.

By jigar

Leave a Reply

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