Default array values in Java

JavaJava Programming Java 8

Java provides a data structure, the array, which stores a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type. When an array is created without assigning it any elements, compiler assigns them the default value. Following are the examples:

  • Boolean - false
  • int - 0
  • double - 0.0
  • Object - null

Example

 Live Demo

public class Tester {
   public static void main(String[] args) {
      System.out.print("Default values (String array):");
      String strings[] = new String[5];
      for (String s : strings) {
         System.out.print(s + " ");
      }
      System.out.println();
      System.out.print("Default values (int array):");
      int numbers[] = new int[5];
      for (int val : numbers) {
         System.out.print(val + " ");
      }
      System.out.println();
      System.out.print("Default values (double array):");
      double doubles[] = new double[5];
      for (double val : doubles) {
         System.out.print(val + " ");
      }
      System.out.println();
      System.out.print("Default values (boolean array):");
      boolean booleans[] = new boolean[5];
      for (boolean val : booleans) {
         System.out.print(val + " ");
      }
      System.out.println();
      System.out.print("Default values (Object array):");
      Tester testers[] = new Tester[5];
      for (Tester val : testers) {
         System.out.print(val + " ");
      }
   }
}

Output

Default values (String array):null null null null null
Default values (int array):0 0 0 0 0
Default values (double array):0.0 0.0 0.0 0.0 0.0
Default values (boolean array):false false false false false
Default values (Object array):null null null null null
raja
Published on 13-Aug-2018 12:53:24
Advertisements