Java Initialize Arrays

In this chapter you will learn:

  1. How to Initialize Java Arrays
  2. Syntax to Initialize Arrays
  3. Example - How to initialize an array during the declaration

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   w  w  w  . j  a v a  2s  . c o m*/
    int days[] = {31, 28, 31,};
    System.out.println("days[2] is " + days[2]);
  }
}

The output:

Next chapter...

What you will learn in the next chapter:

  1. Description for Java Array Index
  2. Example - ArrayIndexOutOfBoundsException
  3. Example - How to access array element by index
Home »
  Java Tutorial »
    Java Langauge »
      Java Array
Java Array
Java Array Variables
Java Array Initial Values
Java Array Length
Java Initialize Arrays
Java Array Index
Java Array for each loop
Java Multidimensional Arrays