Skip to main content

Default value for Array if you will not initialize

What happen if you will not initialize some of array element.
for that compiler give default value.
i.e
for String it is null;
for Integer it is 0;
for double 0.0 like this.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
 
package com.spy.javaforlearn;
 
public class DefaultValue 
{
 
	public static void main(String[] args) 
 
	{
 
 
	    // Declaring int Array of size 3
 
			int[] number=new int[3];
 
 
			//getting size of Array
 
		     System.out.println("Size of Array: "+number.length); 
 
		    //initializing Array
 
		     number[0]=10;
 
		     number[2]=20;
 
		     //accessing array element
 
		     System.out.println("accessing array element");
 
		     for(int i=0;i<number.length;i++)
		      {
		    	 System.out.println(number[i]);	 
		      }
 
	}
}

//Here we did not initialize element at index 1 (number[1]) so compiler give default value 0

Output:

1
2
3
4
5
6
 
Size of Array: 3
accessing array element
10
0
20