Introduction to Arrays

A Java array is an ordered collection of primitives, object references, or other arrays.
Java arrays are homogeneous: except as allowed by polymorphism, all elements of an array must be of the same type.
Each variable is referenced by array name and its index.
Arrays may have one or more dimensions.

One-Dimensional Arrays

A one-dimensional array is a list of similar-typed variables. The general form of a one-dimensional array declaration is:


type var-name[ ];

The following declares an array named days with the type "array of int":


int days[];

Allocate memory for array

You allocate memory using new and assign it to array variables. new is a special operator that allocates memory. The general form is:

arrayVar = new type[size];

The following two statements first create an int type array variable and then allocate memory for it to store 12 int type values.


int days[]; 
days = new int[12];
days refers to an array of 12 integers.
All elements in the array is initialized to zero.

Array creation is a two-step process.

  1. declare a variable of the desired array type.
  2. allocate the memory using new.
In Java all arrays are dynamically allocated.
You can access a specific element in the array with [index].
All array indexes start at zero.
For example, the following code assigns the value 28 to the second element of days.

public class Main {
  public static void main(String[] argv) {
    int days[];
    days = new int[12];

    days[1] = 28;

    System.out.println(days[1]);
  }
}

It is possible to combine the declaration of the array variable with the allocation of the array itself.


int month_days[] = new int[12];

Array Element Initialization Values

Element TypeInitial Value
byte0
int0
float0.0f
char'\u0000'
object referencenull
short0
long0L
double0.0d
booleanfalse
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.