Java Array Initializer

Introduction

The following code uses for loop to initialize array elements.

 
public class Main
{
   public static void main(String[] args)
   {//from  w w w  .  j a va 2s.  c o m
      final int ARRAY_LENGTH = 10; // constant
      int[] array = new int[ARRAY_LENGTH]; // create array
                         
      // calculate value for each array element
      for (int counter = 0; counter < array.length; counter++)
         array[counter] = 2 + 2 * counter;
                         
      System.out.printf("%s%8s%n", "Index", "Value"); // column headings
                            
      // output each array element's value 
      for (int counter = 0; counter < array.length; counter++)
         System.out.printf("%5d%8d%n", counter, array[counter]);
   } 
} 

Initializing the elements of an array with an array initializer.

public class Main
{
   public static void main(String[] args)
   {/*from   w  w w .  j av a2 s .c  o  m*/
      // initializer list specifies the initial value for each element
      int[] array = {2, 7, 4, 8, 9, 10, 9, 13, 17, 19};

      System.out.printf("%s%8s%n", "Index", "Value"); // column headings
   
      // output each array element's value 
      for (int counter = 0; counter < array.length; counter++)
         System.out.printf("%5d%8d%n", counter, array[counter]);
   }
}

Initializing the elements of an array to default values of zero.

public class Main
{
   public static void main(String[] args)
   {//from  ww w .ja va 2  s.c  o m
      // declare variable array and initialize it with an array object  
      int[] array = new int[10]; // new creates the array object 

      System.out.printf("%s%8s%n", "Index", "Value"); // column headings
   
      // output each array element's value 
      for (int counter = 0; counter < array.length; counter++)
         System.out.printf("%5d%8d%n", counter, array[counter]);
   } 
} 



PreviousNext

Related