Java Initialize Arrays

Description

We can initialize the elements in an array with values when declaring it, and at the same time determine how many elements it has.

Syntax

To do this, we simply add an equal sign followed by the list of element values enclosed between braces following the specification of the array variable.

For example, you can define and initialize an array with the following statement:


int[] primes = {2, 3, 5, 7, 11, 13, 17};    // An array of 7 elements 

The array size is determined by the number of initial values.

The values are assigned to the array elements in sequence, so in this example primes[0] has the initial value 2, primes[1] has the initial value 3, primes[2] has the initial value 5, and so on through the rest of the elements in the array.

Example

When an array is initialized during the declaration there is no need to use new.


public class Main {
  public static void main(String args[]) {
/*from  ww  w .j a  v  a2 s .com*/
    int days[] = {31, 28, 31,};
    System.out.println("days[2] is " + days[2]);
  }
}

The output:





















Home »
  Java Tutorial »
    Java Language »




Java Data Type, Operator
Java Statement
Java Class
Java Array
Java Exception Handling
Java Annotations
Java Generics
Java Data Structures