What are the default initialization values of elements in an array using Java?


In Java arrays are the reference types which stores multiple elements of the same datatype. You can create an array just like an object using the new keyword −

type[] reference = new type[10];

or, directly using the flower brackets ({}).

int [] myArray = {10, 20, 30, 40, 50}

When you create instance variables in Java you need to initialize them, else the compiler will initialize on your behalf with default values.

Similarly, if you create an array as instance variable, you need to initialize it else the compiler initializes with default values which are −

  • Integer: 0
  • Byte: 0
  • Float:0.0
  • Boolean: false
  • String/Object: null

Example

In the following Java program prints the default values of the arrays of type integer, float, byte, boolean and, String.

import java.util.Arrays;
import java.util.Scanner;
public class ArrayDefaultValues {
   int intArray[] = new int[3];
   float floatArray[] = new float[3];
   byte byteArray[] = new byte[3];
   boolean boolArray[] = new boolean[3];
   String stringArray[] = new String[3];
   public static void main(String args[]){
      ArrayDefaultValues obj = new ArrayDefaultValues();
      System.out.println(Arrays.toString(obj.intArray));
      System.out.println(Arrays.toString(obj.floatArray));
      System.out.println(Arrays.toString(obj.byteArray));
      System.out.println(Arrays.toString(obj.boolArray));
      System.out.println(Arrays.toString(obj.stringArray));
   }
}

Output

[0, 0, 0]
[0.0, 0.0, 0.0]
[0, 0, 0]
[false, false, false]
[null, null, null]
raja
Published on 02-Aug-2019 16:12:44
Advertisements