What is Array in Java

Array in java are very useful in cases where many elements of the same data types need to be stored and processed. It is also useful in real-time projects to collect the same type of objects and send all the values with a single method call.

What is Array in Java?

An array in java is a group of related variables with the same data type, same name, and fixed number of values. All items in the array are accessed by an index which starts at zero.

A benefit of arrays is the capacity to deal with a large number of related values in one entity.

Arrays are considered as objects in Java.

The indexing of the variable in an array starts from 0.

Arrays in Java are stored in the form of dynamic allocation in the heap area.

Object class is a superclass of the Array.

Types of Array in Java

1) Single Dimensional Array [One Dimensional Array-1D]

2) Multi-Dimensional Array [Two-Dimensional Array-2D]

1) Single Dimensional Array in Java [One Dimensional Array-1D]

A one dimensional array is a sequential collection of variables having the same datatype. We can store various elements in an array.

Syntax 1):

dataType VaribaleName [] = {…, …, …, …, …};

Example:

int ar1[] = {100,200,300,400,500};

Syntax 2):

dataType VaribaleName [] = new dataType [number of data];

Example:

String ar [] = new string [5];

ar [0] =” Pune”;

ar [1] =” Mumbai”;

ar [2] =”UK”;

ar [3] =” South Africa”;

ar [4] =” Delhi”;

2) Multi-Dimensional Array in Java [Two-Dimensional Array-2D]

An array involving two subscripts [] [] is known as a two-dimensional array. – It is arranged as an array of arrays. The representation of the elements is done in the form of rows & columns.

Syntax 1):

dataType VaribaleName [] [] = {{…, …, …,}, {…, …, …,}, {…, …, …,}};

Example:

int ar1[] [] = {{10,20,30}, {15,24,48}, {32,47,65}};

Syntax 2):

dataType VaribaleName [] = new dataType [][];

Example:

String ar [] [] = new string [3] [3]; ar [0] [0] =10;

ar [0] [1] =20;

ar [0] [2] =30;

ar [1] [0] =15;

ar [1] [1] =24;

ar [1] [2] =48;

ar [2] [0] =32;

ar [2] [1] =47;

ar [2] [2] =65;

Java ArraysIndexOutOfBoundsException

A common mistake of all programmers while using arrays is they try to access indexes which are outside the limit.

For example, if an array is of length 6 then the programmers can use any index of the array in between 0 and 5. But sometimes the programmers tries to access elements outside this range. That is when the compiler throws a ArraysIndexOutOfBoundsException error.

Other Popular Articles

What is Lambda Expressions in Java?

Leave a Comment