Create an Array

In this chapter you will learn:

  1. How to declare an array type and allocate memory
  2. What are the default value for different type of array
  3. What are Alternative Array Declaration Syntax
  4. How to initialize an array during the declaration

Array creation is a two-step process

There are two steps involved in array creation:

  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[];/*j av a  2 s .c  o  m*/
    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

Different types of array have different default value. For most of the primitive types the default value is 0. For object array the default value is null. The following table lists the default value for various array types.

Element Type Initial Value
byte 0
int 0
float 0.0f
char '\u0000'
object referencenull
short 0
long 0L
double 0.0d
boolean false

Alternative Array Declaration Syntax

The square brackets follow the type specifier, and not the name of the array variable.

type[] var-name;

For example, the following two declarations are equivalent:

int al[] = new int[3]; 
int[] a2 = new int[3];

The following declarations are also equivalent:

char d1[][] = new char[3][4]; 
char[][] d2 = new char[3][4];

Arrays can be initialized when they are declared

When an array is initialized when they are declared the array will be created large enough to hold the number of elements. And there is no need to use new.

public class Main {
  public static void main(String args[]) {
//java2s. 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. How to access array element by index
  2. How to get the array length
Home » Java Tutorial » Array
Java Array
Create an Array
Array Index and length
Multidimensional Arrays
Array examples
Array copy
Array compare
Array Binary search
Array Search
Array sort
Array to List
Convert array to Set
Array fill value
Array to String
Array element reverse
Array element delete
Array shuffle
Array element append
Array min / max value
Sub array search
Get Sub array
Array dimension reflection
Array clone