Arrays

192 views.

An array is a derived data type, which can be used for strong multiple values.

If an application requires multiple values, then we can store those multiple values by declaring multiple variables. If we declare multiple variables in a program then the code size will increase, and readability will be reduced.

In order to reduce the code size, and improve the readability of the code, we take the help of arrays. Arrays in java language are classified into two type. They are

  1. Single dimension array
  2. Multi dimension array

Single dimension array:

Single dimension array is a collection of multiple values represented in the form of a single row or single column.

Syntax for declaring a single dimension array:

datatype  arrayName[];  each pair of square bracket represents one dimension.

The name of the array can be any valid java identifier.

Rule1:

At the time of array declaration we can specify the pair of [] either before the array name or after the array name.

Example:

int rollNo[];

double[] marks;

char[] grade;

boolean result[];

Rule2:

 At the time of array  declaration we should not specify the size of the array.

Syntax for declaring a single dimension array:

datatype arrayName[]=new datatype[size];

Or

datatype arrayName[];

arrayName=new datatype[size];

Example:

int arr[]=new datatype[10];

or

int arr[];

arr=new int[10];

Rule3:

Specifying the size of the array at the time of array creation is mandatory and it should be of byte, short, int, char type only.

The size of the array must be a positive number. If a negative number is specified, then we get a runtime error NegativeArraySizeException.

When an array is created, the memory for that array will be allocated in sequential memory locations. The amount of memory allocated to an array depends upon the size of the array and the size of the data type of the array. Once the memory for the array is allocated, all the array elements will be initialized automatically with default values.

An array contains multiple values and for the entire array have only one name. In order to access the array elements we take the help of index position. The index position will always begin with 0. The range of the index position will be 0 size -1;

Every array internally an object and it contains a default variable called length, which represents the size of the array.

int arr[]=new int[10];

arrayName[index]=starting address of the array+ index* size of array type

arr[0]=1000+0*4=1000;

arr[1]=1000+1*4=1024;

arr[5]=1000+5*4=1020;

Syntax for accessing the array elements:

arrayName[index]

Example:

arr[0]

arr[1]

When we are accessing the array elements, we are supposed to specify the index position within the range otherwise we get runtime error called ArrayIndexOutofBoundException.

Syntax to assign a value to an array element:

arrayName[index]=value;

Example:

arr[0]=10;

arr[1]=20;

Leave a Reply