Skip to content
Related Articles

Related Articles

What happens Array is not initialized?

Improve Article
Save Article
  • Last Updated : 02 Nov, 2022
Improve Article
Save Article

As the array is an important data structure for the coding perspective, there are some conditions that need to be careful. As in any language, there are two different methods to initialize the array:

  • While declaring the array
  • Any time after declaring the array

Shown below are the two ways of initializing an array

Initializing the array at the time of declaration:

Syntax

int arr[] = {1, 2, 3, 4, 5};

Initializing the array after declaration:

Syntax

int arr[5];
for (int i = 0; i < 5; i++)
    arr[i] = i + 1;

Why is there a need to initialize an Array?

If the array is not initialized at the time of declaration or any time after that then it will contain some random values in each memory position. These random values can be of two types: 

1. Default values.

1.1 If the array elements are of object types then the default value is null.

Java




import java.io.*;
 
class GFG {
    public static void main(String[] args)
    {
        Integer[] array = new Integer[5];
        for (Integer p : array) {
            System.out.print(p + " ");
        }
    }
}


Output

null null null null null 

1.2. If the array elements are of primitive data types then the default value is 0.

Java




import java.io.*;
 
class GFG {
    public static void main(String[] args)
    {
        int[] array = new int[5];
        for (int p : array) {
            System.out.print(p + " ");
        }
    }
}


Output

0 0 0 0 0 

2. Garbage value:

C++




#include <bits/stdc++.h>
using namespace std;
 
int main()
{
    int array[5];
    for (int p : array)
        cout << p << " ";
    return 0;
}


Output

4196608 0 4196144 0 -1374567488 

Default values in Javascript

Javascript




<script>
let arr = new Array(5);
 
for(x of arr){
    document.write(x + "<br>");
}
</script>


Output:

undefined
undefined
undefined
undefined
undefined

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!