Dynamic arrays in Java | Static arrays in Java

By now I’m sure you have a clear idea on variables and constants in Java. Suppose you’re asked to store a number, say 5 in a variable. You’ll obviously declare a variable and assign it a value of 5 using assignment operator ‘=’.  E.g. int n=5;

Now if I tell you to store 10 numbers say 0,1,2,3,4,5,6,7,8,9 what would you do?

Will you declare 10 variables like int n1=0; int n2=1; ………..int n10=9; Let us assume out of compulsion you’re doing this but what if I ask you to store 100 numbers, will you declare 100 variables?

Thus to present a solution to this hectic task, the concept of data structures are introduced in Java.

Data structures are nothing but a structure that is used to store multiple data in an organized manner. One of the most commonly used data structure is Array.

Arrays are homogeneous data structures that are used to store data in a sequential manner.

By homogeneous, it means data stored in an array will be of similar data type, i.e. an integer array will store only to integers and a character array will store only characters.

Types of an array:

There are two types of array:

  • Static Array
  • Dynamic Array

Static Array in Java

Static Arrays are arrays that are declared before runtime and are assigned values while writing the code.

The syntax of declaring a static array is:

<data type>  <variable name> []={<data1>,<data2>,…..<dataN>};


int arr[]={2,5,6,9,7,4,3};

Dynamic Array in Java

Dynamic Arrays are arrays that are declared while writing the code and are assigned values in run-time.

The syntax of declaring a dynamic array is:

<data type> <variable name> [ <No. of elements to be stored in array>];


int arr[10];

will declare an array that will have 10 pockets(empty space) and the indexing of the array cells will start from 0.

How to input in a dynamic array?

int i,n=10 ;

int arr[n];

for (i=0;i<n;i++)


System.out.println(“\n Enter: “);

arr[i]=<input function>;



Here i is the loop control variable or LCV and n stores the total number of elements to be stored. The for-loop is initialized with the value of 0 which is the initial index number of the array cells. As the loop runs, it increments the LCV and thus the values are stored in a sequential manner.

The input function will be discussed in the upcoming lessons.


Dynamic arrays in Java | Static arrays in Java