Skip to content
Related Articles
Open in App
Not now

Related Articles

What happens Array is not initialized?

Improve Article
Save Article
Like Article
  • Last Updated : 22 Feb, 2023
Improve Article
Save Article
Like 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 + " ");
        }
    }
}


Python3




# code
arr = [None]*5
print(arr)
 
#this code is contributed by Akshay Tripathi(akshaytripathi630)


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 + " ");
        }
    }
}


Python3




# code
arr = [0]*5
print(arr)
 
#this code is contributed by Akshay Tripathi(akshaytripathi630)


C#




using System;
 
public class GFG
{
   static public void Main (){
        int[] array = new int[5];
        foreach (int p in array)
        {
            Console.Write(p + " ");
        }
    }
}
 
// This code is contributed by akashish__


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
Like Article
Save Article
Related Articles

Start Your Coding Journey Now!