Home » Static Array in Java

Static Array in Java

by Online Tutorials Library

Static Array in Java

In Java, array is the most important data structure that contains elements of the same type. It stores elements in contiguous memory allocation. There are two types of array i.e. static array and dynamic array. In this section, we will focus only on static array in Java.

Static Array

An array that is declared with the static keyword is known as static array. It allocates memory at compile-time whose size is fixed. We cannot alter the static array.

If we want an array to be sized based on input from the user, then we cannot use static arrays. In such a case, dynamic arrays allow us to specify the size of an array at run-time.

Static Array Example

For example, int arr[10] creates an array of size 10. It means we can insert only 10 elements; we cannot add a 11th element as the size of Array is fixed.

Advantages of Static Array

  • It has efficient execution time.
  • The lifetime of static allocation is the entire run time of the program.

Disadvantages of Static Array

  • In case more static data space is declared than needed, there is waste of space.
  • In case less static space is declared than needed, then it becomes impossible to expand this fixed size during run time.

Declaring a Static Array

The syntax to declare a static array is:

For example:

We can also declare and initialize static array as follows:

Static array can also be declared as a List. For example:

Static Array Java Program

StaticArrayExample.java

Output:

Welcome to TutorAspire 

Let’s see another Java program.

StaticArrayExample.java

Output:

1  2  3  4  5  

Difference Between Static Array and Dynamic Array

The following table describes the key differences between static array and dynamic array.

Static Array Dynamic Array
Static arrays are allocated memory at compile time. Dynamic array is located at run-time.
The size of static array is fixed. The size of dynamic array is fixed.
It is located in stack memory space. It is located in heap memory space.
int array[10]; //array of size 10 int* array = new int[10];

You may also like