Arrays
Arrays:- It is a collection of the variable of the same type that have memory location. we can store a fixed set of elements in an Array. An Array in Java is index-based, the first element of the array is stored at 0 index, to find the length of an array We use the property called array_name.length.
Types of Array:-
There are two types of Arrays.
1)- Single dimensional array:-
2)- Multi-dimensional array:-
1)- Single dimensional array:-
Creating a single-dimensional array is very simple. It is kind of row with the number of columns, Where each column access with 0 based index. It is also referred to as the linear array.
A set of similar datatypes by which uses a single column/ index is called as single-dimensional array.
Syntax:- type array_name = new datatype[size];
Ex. of creating array:-
first Way:-
class arrayexample
{
public static void main(String args[])
{
int a = new int[5];
a[0] = 10;
a[1] = 20;
a[2] = 30;
a[3] = 40;
a[4] = 50;
for(int i = 0; i<5; i++)
{
System.out.println("a[i]");
}
}
}
Second way:-
class arrayexample1
{
public void main(String main[])
{
int a = {10, 20, 30, 40, 50};
for(int i = 0; i<5; i++)
{
System.out.println("a[i]");
}
}
}
Here, new is a keyword that allocates memory.
-All array indexes start at zero. The computer reserves five storage locations as shown below.
-If we want to assign values to these arrays elements. it can be assign as.
Ex. of creating array:-
first Way:-
class arrayexample
{
public static void main(String args[])
{
int a = new int[5];
a[0] = 10;
a[1] = 20;
a[2] = 30;
a[3] = 40;
a[4] = 50;
for(int i = 0; i<5; i++)
{
System.out.println("a[i]");
}
}
}
Second way:-
class arrayexample1
{
public void main(String main[])
{
int a = {10, 20, 30, 40, 50};
for(int i = 0; i<5; i++)
{
System.out.println("a[i]");
}
}
}
Here, new is a keyword that allocates memory.
-All array indexes start at zero. The computer reserves five storage locations as shown below.
Index |
a[0] = 10;
a[1] = 20;
a[2] = 30;
a[3] = 40;
a[4] = 50;
-The above statements will make the above array filled by all assigned values and array will be.
memory allocation |
2)- Multi-dimensional array:-
A Multi-dimensional array is also known as a rectangular array is an array with more than one dimension. The form of Multi-dimensional array is a matrix in it two or more 0 based index is used to access to a particular value in the array.
Syntax:- type array_name[rows][column] = new datatype[row size][column size];
First way:-
class MDarrayexample
{
public static void main(String args[])
{
int a[][] = new int[2][2];
a[0][0] = 10;
a[0][1] = 20;
a[1][0] = 30;
a[1][1] = 40;
for(int i = 0; i<2; i++)
{
for(int j = 0; j>2; j++)
{
System.out.println("a[i][j]");
}
}
}
}
Second way:-
class arrayexample1
{
public void main(String main[])
{
int a = {{10, 20},{30, 40}};
for(int i = 0; i<2; i++)
{
for(int j = 0; j>2; j++)
{
System.out.println("a[i][j]");
}
}
}
}
0 Comments