Arrays in java

What is Array

  • Arrays are used to store homogenous elements/values (of same data type)
  • Can access the elements by the indexes.
  • Index always start from zero (0).
  • Arrays can be single or multi dimensional

Watch demo –

Let’s see some of the implementation of the array.

One dimensional array:

dataType[] varName  //declaring array variable
varName = new dataTyp[Size of array]
e.g: int a[]; or int[] a;
a = new int[2];

So we have 2 ways to declare and assign values:

  • Declare the array variable and specify the size, and then assign values to each index
  • Declare and assign values then n there, no need to specify the size.

Two dimensional array:

Let’s see different ways of declaring, assigning and accessing 2 dimensional array in java –

Like this we can have multi dimentional array.
Limitations of arrays:

  • Arrays can have only homogenius elements (same data type).
  • Array size is fixed (once we declared the size, we can not alter it)

If we declare the size of array, then we can have less number of elements(waste of rest size) or may be we need to insert more elements than the assigned size (can’s increase the size).

  • Not all ready made methods are not present for arrays

e.g sorting, Inserting elements in some order, to search an element in side array.

To overcome this limitations, we normally use collections framework (List / Set / hashMap),
but it is highly recomended to use Arrays if we already know the size, we will be discussing this in
collections framework topic.

Content posted is based on learning or working experience,
Share the post with others if find useful,
Any queries?, leave comments or discuss on our, Thanks!

Leave a Reply

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