Array Default Values in Java

Whenever you create a new array, Java automatically fills each element with a default value. Once the array is constructed, a new array is allocated in heap memory based on the array's type. In this article, we will look at what the default values of an array are in Java.

The default values assigned to array elements are listed below.

  • boolean: false
  • int : 0
  • double : 0.0
  • String: null
  • User-Defined Type: null
class ClassOne 
{
   public static void main(String[] args) 
   {
	 // Declaring an int type array
	 int intArray[] = new int[2]; 
	 // Print all elements of intArray
	 for (int i = 0; i < intArray.length; i++) 
	   System.out.println("Elements of intArray = " + intArray[i]);
	// Declaring an boolean type array
	boolean[] booleanArray = new boolean[2]; 
	// Print all elements of booleanArray
	for (int i = 0; i < booleanArray.length; i++) 
	   System.out.println("Elements of booleanArray = " + booleanArray[i]);
	// Declaring an String type array
	String[] stringArray = new String[2]; 
	// Print all elements of stringArray
	for (int i = 0; i < stringArray.length; i++) 
	   System.out.println("Elements of stringArray = " + stringArray[i]);
  }
}

Output: Elements of intArray = 0
Elements of intArray = 0
Elements of booleanArray = false
Elements of booleanArray = false
Elements of stringArray = null
Elements of stringArray = null

Leave a Comment

Knowing these defaults helps you avoid surprises when reading array elements before assigning them. Primitive arrays start with zero-like values, while reference-type arrays such as String or user-defined types start with null, so always check for null before using those elements.

Follow us on Instagram & watch the latest videos on YouTube. Click below social icons to visit our Instagram & YouTube profiles.