Question

How do I declare and initialize an array in Java?

Was it helpful?

Solution

You can either use array declaration or array literal (but only when you declare and affect the variable right away, array literals cannot be used for re-assigning an array).

For primitive types:

int[] myIntArray = new int[3];
int[] myIntArray = {1, 2, 3};
int[] myIntArray = new int[]{1, 2, 3};

For classes, for example String, it's the same:

String[] myStringArray = new String[3];
String[] myStringArray = {"a", "b", "c"};
String[] myStringArray = new String[]{"a", "b", "c"};

The third way of initializing is useful when you declare the array first and then initialize it. The cast is necessary here.

String[] myStringArray;
myStringArray = new String[]{"a", "b", "c"};

OTHER TIPS

There are two types of array.

One Dimensional Array

Syntax for default values:

int[] num = new int[5];

Or (less preferred)

int num[] = new int[5];

Syntax with values given (variable/field initialization):

int[] num = {1,2,3,4,5};

Or (less preferred)

int num[] = {1, 2, 3, 4, 5};

Note: For convenience int[] num is preferable because it clearly tells that you are talking here about array. Otherwise no difference. Not at all.

Multidimensional array

Declaration

int[][] num = new int[5][2];

Or

int num[][] = new int[5][2];

Or

int[] num[] = new int[5][2];

Initialization

 num[0][0]=1;
 num[0][1]=2;
 num[1][0]=1;
 num[1][1]=2;
 num[2][0]=1;
 num[2][1]=2;
 num[3][0]=1;
 num[3][1]=2;
 num[4][0]=1;
 num[4][1]=2;

Or

 int[][] num={ {1,2}, {1,2}, {1,2}, {1,2}, {1,2} };

Ragged Array (or Non-rectangular Array)

 int[][] num = new int[5][];
 num[0] = new int[1];
 num[1] = new int[5];
 num[2] = new int[2];
 num[3] = new int[3];

So here we are defining columns explicitly.
Another Way:

int[][] num={ {1}, {1,2}, {1,2,3,4,5}, {1,2}, {1,2,3} };

For Accessing:

for (int i=0; i<(num.length); i++ ) {
    for (int j=0;j<num[i].length;j++)
        System.out.println(num[i][j]);
}

Alternatively:

for (int[] a : num) {
  for (int i : a) {
    System.out.println(i);
  }
}

Ragged arrays are multidimensional arrays.
For explanation see multidimensional array detail at the official java tutorials

Type[] variableName = new Type[capacity];

Type[] variableName = {comma-delimited values};



Type variableName[] = new Type[capacity]; 

Type variableName[] = {comma-delimited values};

is also valid, but I prefer the brackets after the type, because it's easier to see that the variable's type is actually an array.

There are various ways in which you can declare an array in Java:

float floatArray[]; // Initialize later
int[] integerArray = new int[10];
String[] array = new String[] {"a", "b"};

You can find more information in the Sun tutorial site and the JavaDoc.

The following shows the declaration of an array, but the array is not initialized:

 int[] myIntArray = new int[3];

The following shows the declaration as well as initialization of the array:

int[] myIntArray = {1,2,3};

Now, the following also shows the declaration as well as initialization of the array:

int[] myIntArray = new int[]{1,2,3};

But this third one shows the property of anonymous array-object creation which is pointed by a reference variable "myIntArray", so if we write just "new int[]{1,2,3};" then this is how anonymous array-object can be created.

If we just write:

int[] myIntArray;

this is not declaration of array, but the following statement makes the above declaration complete:

myIntArray=new int[3];

I find it is helpful if you understand each part:

Type[] name = new Type[5];

Type[] is the type of the variable called name ("name" is called the identifier). The literal "Type" is the base type, and the brackets mean this is the array type of that base. Array types are in turn types of their own, which allows you to make multidimensional arrays like Type[][] (the array type of Type[]). The keyword new says to allocate memory for the new array. The number between the bracket says how large the new array will be and how much memory to allocate. For instance, if Java knows that the base type Type takes 32 bytes, and you want an array of size 5, it needs to internally allocate 32 * 5 = 160 bytes.

You can also create arrays with the values already there, such as

int[] name = {1, 2, 3, 4, 5};

which not only creates the empty space but fills it with those values. Java can tell that the primitives are integers and that there are 5 of them, so the size of the array can be determined implicitly.

Alternatively,

// Either method works
String arrayName[] = new String[10];
String[] arrayName = new String[10];

That declares an array called arrayName of size 10 (you have elements 0 through 9 to use).

Also, in case you want something more dynamic there is the List interface. This will not perform as well, but is more flexible:

List<String> listOfString = new ArrayList<String>();

listOfString.add("foo");
listOfString.add("bar");

String value = listOfString.get(0);
assertEquals( value, "foo" );

There are two main ways to make an array:

This one, for an empty array:

int[] array = new int[n]; // "n" being the number of spaces to allocate in the array

And this one, for an initialized array:

int[] array = {1,2,3,4 ...};

You can also make multidimensional arrays, like this:

int[][] array2d = new int[x][y]; // "x" and "y" specify the dimensions
int[][] array2d = { {1,2,3 ...}, {4,5,6 ...} ...};

Take the primitive type int for example. There are several ways to declare and int array:

int[] i = new int[capacity];
int[] i = new int[] {value1, value2, value3, etc};
int[] i = {value1, value2, value3, etc};

where in all of these, you can use int i[] instead of int[] i.

With reflection, you can use (Type[]) Array.newInstance(Type.class, capacity);

Note that in method parameters, ... indicates variable arguments. Essentially, any number of parameters is fine. It's easier to explain with code:

public static void varargs(int fixed1, String fixed2, int... varargs) {...}
...
varargs(0, "", 100); // fixed1 = 0, fixed2 = "", varargs = {100}
varargs(0, "", 100, 200); // fixed1 = 0, fixed2 = "", varargs = {100, 200};

Inside the method, varargs is treated as a normal int[]. Type... can only be used in method parameters, so int... i = new int[] {} will not compile.

Note that when passing an int[] to a method (or any other Type[]), you cannot use the third way. In the statement int[] i = *{a, b, c, d, etc}*, the compiler assumes that the {...} means an int[]. But that is because you are declaring a variable. When passing an array to a method, the declaration must either be new Type[capacity] or new Type[] {...}.

Multidimensional Arrays

Multidimensional arrays are much harder to deal with. Essentially, a 2D array is an array of arrays. int[][] means an array of int[]s. The key is that if an int[][] is declared as int[x][y], the maximum index is i[x-1][y-1]. Essentially, a rectangular int[3][5] is:

[0, 0] [1, 0] [2, 0]
[0, 1] [1, 1] [2, 1]
[0, 2] [1, 2] [2, 2]
[0, 3] [1, 3] [2, 3]
[0, 4] [1, 4] [2, 4]

If you want to create arrays using reflections then you can do like this:

 int size = 3;
 int[] intArray = (int[]) Array.newInstance(int.class, size ); 

Declaring an array of object references:

class Animal {}

class Horse extends Animal {
    public static void main(String[] args) {

        /*
         * Array of Animal can hold Animal and Horse (all subtypes of Animal allowed)
         */
        Animal[] a1 = new Animal[10];
        a1[0] = new Animal();
        a1[1] = new Horse();

        /*
         * Array of Animal can hold Animal and Horse and all subtype of Horse
         */
        Animal[] a2 = new Horse[10];
        a2[0] = new Animal();
        a2[1] = new Horse();

        /*
         * Array of Horse can hold only Horse and its subtype (if any) and not
           allowed supertype of Horse nor other subtype of Animal.
         */
        Horse[] h1 = new Horse[10];
        h1[0] = new Animal(); // Not allowed
        h1[1] = new Horse();

        /*
         * This can not be declared.
         */
        Horse[] h2 = new Animal[10]; // Not allowed
    }
}

In Java 9

Using different IntStream.iterate and IntStream.takeWhile methods:

int[] a = IntStream.iterate(10, x -> x <= 100, x -> x + 10).toArray();

Out: [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]


int[] b = IntStream.iterate(0, x -> x + 1).takeWhile(x -> x < 10).toArray();

Out: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

In Java 10

Using the Local Variable Type Inference:

var letters = new String[]{"A", "B", "C"};

Array is a sequential list of items

int item = value;

int [] one_dimensional_array = { value, value, value, .., value };

int [][] two_dimensional_array =
{
  { value, value, value, .. value },
  { value, value, value, .. value },
    ..     ..     ..        ..
  { value, value, value, .. value }
};

If it's an object, then it's the same concept

Object item = new Object();

Object [] one_dimensional_array = { new Object(), new Object(), .. new Object() };

Object [][] two_dimensional_array =
{
  { new Object(), new Object(), .. new Object() },
  { new Object(), new Object(), .. new Object() },
    ..            ..               ..
  { new Object(), new Object(), .. new Object() }
};

In case of objects, you need to either assign it to null to initialize them using new Type(..), classes like String and Integer are special cases that will be handled as following

String [] a = { "hello", "world" };
// is equivalent to
String [] a = { new String({'h','e','l','l','o'}), new String({'w','o','r','l','d'}) };

Integer [] b = { 1234, 5678 };
// is equivalent to
Integer [] b = { new Integer(1234), new Integer(5678) };

In general you can create arrays that's M dimensional

int [][]..[] array =
//  ^ M times [] brackets

    {{..{
//  ^ M times { bracket

//            this is array[0][0]..[0]
//                         ^ M times [0]

    }}..}
//  ^ M times } bracket
;

It's worthy to note that creating an M dimensional array is expensive in terms of Space. Since when you create an M dimensional array with N on all the dimensions, The total size of the array is bigger than N^M, since each array has a reference, and at the M-dimension there is an (M-1)-dimensional array of references. The total size is as following

Space = N^M + N^(M-1) + N^(M-2) + .. + N^0
//      ^                              ^ array reference
//      ^ actual data

For creating arrays of class Objects you can use the java.util.ArrayList. to define an array:

public ArrayList<ClassName> arrayName;
arrayName = new ArrayList<ClassName>();

Assign values to the array:

arrayName.add(new ClassName(class parameters go here);

Read from the array:

ClassName variableName = arrayName.get(index);

Note:

variableName is a reference to the array meaning that manipulating variableName will manipulate arrayName

for loops:

//repeats for every value in the array
for (ClassName variableName : arrayName){
}
//Note that using this for loop prevents you from editing arrayName

for loop that allows you to edit arrayName (conventional for loop):

for (int i = 0; i < arrayName.size(); i++){
    //manipulate array here
}

In Java 8 you can use like this.

String[] strs = IntStream.range(0, 15)  // 15 is the size
    .mapToObj(i -> Integer.toString(i))
    .toArray(String[]::new);

Declare and initialize for Java 8 and later. Create a simple integer array:

int [] a1 = IntStream.range(1, 20).toArray();
System.out.println(Arrays.toString(a1));
// Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

Create a random array for integers between [-50, 50] and for doubles [0, 1E17]:

int [] a2 = new Random().ints(15, -50, 50).toArray();
double [] a3 = new Random().doubles(5, 0, 1e17).toArray();

Power-of-two sequence:

double [] a4 = LongStream.range(0, 7).mapToDouble(i -> Math.pow(2, i)).toArray();
System.out.println(Arrays.toString(a4));
// Output: [1.0, 2.0, 4.0, 8.0, 16.0, 32.0, 64.0]

For String[] you must specify a constructor:

String [] a5 = Stream.generate(()->"I will not squeak chalk").limit(5).toArray(String[]::new);
System.out.println(Arrays.toString(a5));

Multidimensional arrays:

String [][] a6 = List.of(new String[]{"a", "b", "c"} , new String[]{"d", "e", "f", "g"})
    .toArray(new String[0][]);
System.out.println(Arrays.deepToString(a6));
// Output: [[a, b, c], [d, e, f, g]]

You can also do it with java.util.Arrays:

List<String> number = Arrays.asList("1", "2", "3");

Out: ["1", "2", "3"]

This one is pretty simple and straightforward. I didn't see it in other answers so I thought I could add it.

Another way to declare and initialize ArrayList:

private List<String> list = new ArrayList<String>(){{
    add("e1");
    add("e2");
}};

With local variable type inference you only have to specify type once:

var values = new int[] { 1, 2, 3 };

or

int[] values = { 1, 2, 3 }

Lot of answers here. Adding few tricky way to create arrays ( From an exam point of view its good to know this )

  1. declare and define an array

    int intArray[] = new int[3];
    

this will create an array of length 3. As it holds primitive type int all values set to 0 by default.For example

    intArray[2]; // will return 0
  1. Using box brackets [] before variable name

    int[] intArray = new int[3];
    intArray[0] = 1;  // array content now {1,0,0}
    
  2. Initialise and provide data to array

    int[] intArray = new int[]{1,2,3};
    

    this time no need to mention the size in box bracket. Even simple variant of this is

    int[] intArray = {1,2,3,4};
    
  3. An array of length 0

    int[] intArray = new int[0];
    int length = intArray.length; // will return length 0
    

    Similar for multi-dimensional arrays

    int intArray[][] = new int[2][3]; 
    // This will create an array of length 2 and 
    //each element contains another array of length 3.
    // { {0,0,0},{0,0,0} } 
    int lenght1 = intArray.length; // will return 2
    int length2 = intArray[0].length; // will return 3
    

    Using box brackets before variable

    int[][] intArray = new int[2][3];
    

    its absolutely fine if you put one box bracket at the end

    int[] intArray [] = new int[2][4];
    int[] intArray[][] = new int[2][3][4]
    

Some examples

    int [] intArray [] = new int[][] {{1,2,3},{4,5,6}};
    int [] intArray1 [] = new int[][] {new int[] {1,2,3}, new int [] {4,5,6}};
    int [] intArray2 [] = new int[][] {new int[] {1,2,3},{4,5,6}} 
    // All the 3 arrays assignments are valid
    //Array looks like {{1,2,3},{4,5,6}}

Its not mandatory that each inner element is of the same size.

    int [][] intArray = new int[2][];
    intArray[0] = {1,2,3};
    intArray[1] = {4,5};
    //array looks like {{1,2,3},{4,5}}

    int[][] intArray = new int[][2] ; // this won't compile keep this in mind.

You have to make sure if you are using above syntax , forward direction you have to specify the values in box brackets.Else it won't compile. Some examples :

    int [][][] intArray = new int[1][][];
    int [][][] intArray = new int[1][2][];
    int [][][] intArray = new int[1][2][3]; 

Another important feature is covariant

    Number[] numArray = {1,2,3,4};   // java.lang.Number
    numArray[0] = new Float(1.5f);   // java.lang.Float
    numArray[1] = new Integer(1);    // java.lang.Integer
   //You can store a subclass object in an array that is declared
   // to be of the type of its superclass. 
   // Here Number is the superclass for both Float and Integer.

   Number num[] = new Float[5]; // this is also valid

IMP : For referenced types default value stored to array is null.

Declare Array: int[] arr;

Initialize Array: int[] arr = new int[10]; 10 represents the number of elements allowed in the array

Declare Multidimensional Array: int[][] arr;

Initialize Multidimensional Array: int[][] arr = new int[10][17]; 10 rows and 17 columns and 170 elements because 10 times 17 is 170.

Initializing an array means specifying the size of it.

int[] SingleDimensionalArray = new int[2]

int[][] MultiDimensionalArray = new int[3][4]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top