Arrays

  • An array is an indexed collection of fixed number of homogeneous data elements.
  • The main advantage of arrays is we can represent a group of values with single name hence readability of the code will be improved.
  • The main limitation of arrays is they are fixed in size.i.e once we constructed an array there is no chance of increasing or decreasing bases on our requirement.
  • The first element of array start with zero.

Using an array in your program is a 3 step process

  • Declaring you array.
  • Constructing your array
  • Initializing your array.
public static void main(String[] a)
{
/*
* int[] array_variable is Declaring Array
* new int[5] is Constructing an Array
* array_variable[0]=1 is Initializing Array
* array_variable[i] is accessing array
*/
int[] array_variable=new int[5];
array_variable[0]=1;
array_variable[2]=3;
for(int i=0;i<array_variable.length;i++)
{
System.out.println("the value is"+i+"::"+array_variable[i]);
}
/
**
initilizating array at the time construction only
*/
int[] array_={1,2,3};
for(int i=0;i<array_.length;i++)
{S
ystem.out.println("the value array_ is"+i+"::"+array_[i]);
}
}
####output####
the value is0::1
the value is1::0
the value is2::3
the value is3::0
the value is4::0
the value array_ is0::1
the value array_ is1::2
the value array_ is2::3

Multidimensional Arrays

  • A multidimensional array is a series of arrays so that each array contains its own sub-array(s)

Syntax

Element type[][] array_name=new element_type[size][size];

Multidimensional arrays rules

  • When you allocate memory for a multidimensional array, you need only specify the memory for the first (leftmost) dimension.
  • You can allocate the remaining dimensions separately.
  • In Java the length of each array in a multidimensional array is under your control.

Eg
Int [][] My_array_variable=new int[10][10];

public static void main(String[] a)
{
int [][] My_array_variable=new int[2][3];
My_array_variable[0][0]=1;
My_array_variable[0][1]=2;
My_array_variable[0][2]=3;
My_array_variable[1][0]=4;
My_array_variable[1][1]=5;
My_array_variable[1][2]=6;
for(int i=0;i<2;i++)
{
for(int j=0;j<3;j++)
{
System.out.println("the value of My_array_variable
["+i+"]["+j+"]::"+My_array_variable[i][j]);
}
}
}
####output####
the value of My_array_variable[0][0]::1
the value of My_array_variable[0][1]::2
the value of My_array_variable[0][2]::3
the value of My_array_variable[1][0]::4
the value of My_array_variable[1][1]::5
the value of My_array_variable[1][2]::6

Uses of arrays

  • You can declare an array to work with a set of values of the same data type.
  • An array is a single variable with many compartments to store values, while a scalar variable (that is, not an array) has only one storage compartment in which it can store only one value.
  • You can refer to the array as a whole when you want to refer to all the values it holds, or you can refer to its individual elements one at a time.