By bestattendance


2009-07-29 14:22:27 8 Comments

How do I declare and initialize an array in Java?

19 comments

@Oleksandr 2018-02-21 12:45:00

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"};

@Chamly Idunil 2018-03-08 18:21:39

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);

@Kirill Podlivaev 2017-08-25 13:27:27

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]]

@Peter Mortensen 2018-02-21 22:38:19

Are -50 and/or +50 actually included? That is, is the internal open at one or both ends?

@Kirill Podlivaev 2018-03-21 09:56:34

-50 is included and +50 is excluded. This information from java api "given origin (inclusive) and bound (exclusive)." I use interval declaration from wiki . So I think it will be more correct [-50, 50)

@glmxndr 2009-07-29 14:25:23

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"};

@Quazi Irfan 2015-04-10 03:23:18

What's the purpose of having both the second and third way to do it?

@Skylar Ittner 2015-04-16 17:44:44

@iamcreasy It looks like the second way doesn't work with return statements. return {1,2,3} gives an error, while return new int[]{1,2,3} works fine (assuming of course that your function returns an integer array).

@Quazi Irfan 2015-04-18 04:41:45

@SkylarMT But we can still use the first way to use with return statement.

@Skylar Ittner 2015-04-20 06:09:02

@iamcreasy I recently wrote a function that returned an array of ints. If an error happened inside the function, I wanted it to return a certain value, but the function needed to return an array. Which way works for a one-liner return statement? Only the third one.

@peterflynn 2015-06-03 19:18:17

It's not true that "array literals cannot be used for re-assigning an array" - the third syntax can be used to re-assign an array at any time.

@Jezzamon 2015-07-26 11:43:43

The contents of an array cannot be set using an array literal. Array literals will create a new array each time as opposed to modifying the contents of the previous one. You can store this in an existing variable if you want, so the new array will replace the previous array.

@Khaled.K 2015-10-21 12:22:56

This answer seem incomplete to me, it is missing the part on Array of classes\objects, using String or primitive-datatype-autoboxing to demonstrate the case of classes is misleading.

@M. Usman Khan 2016-01-11 13:53:02

what if i have a parameter in the constructor? e.g. I have constructor public MyClass(int something){}; and I want to initialize array MyClass[] objs = new MyClass[3] (88);

@apadana 2016-05-20 20:49:41

The 2nd form also can't be used to pass into a function. It gives an error. The 3rd form is fine. But I am not sure why the 2nd form can't be used for return or passing to a function? I would like to understand what happens behind the scene.

@teukkam 2016-10-18 09:55:57

@apadana In the second case you are creating an anonymous object which is only defined in the enclosing scope (function or whatever). After returning it to the caller, it is no longer valid. Using the new keyword you allocate the new object from the heap and it is valid outside the defining scope.

@MrAP 2017-04-06 21:47:03

What do you mean by: "but only when you declare and affect the variable right away, array literals cannot be used for re-assigning an array"?

@djangofan 2017-05-29 17:54:52

Why does this work? public class Test { public static void main(String args[]) { final double[] doubles = {2.3, 2.4}; final long[] longs = {2,4L,6,8}; }}

@Habeeb Perwad 2018-02-15 10:52:23

The vote shows 2012. who will make it 2018?

@www-0av-Com 2018-04-04 12:06:05

For newbies, state why you are giving triplicate answers. As a newbie, I thought I needed all 3 lines! Not impressed that first answer gets all the votes, even tho misleading. @codecubed has a much better simple answer.

@Anirudh 2009-07-29 14:28:14

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.

@Clement.Xu 2017-08-04 07:42:26

Another way to declare and initialize ArrayList:

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

@Samuel Newport 2016-08-08 10:01:28

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
}

@codecubed 2016-01-28 19:19:41

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 ...} ...};

@ravi 2015-10-16 10:18:50

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
    }
}

@Isabella Engineer 2013-07-09 21:59:39

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

@vipin8169 2017-02-19 00:25:01

Won't the first one lead to a null/empty array, instead of array with default values?

@AdamIJK 2017-04-26 11:26:38

I agree on that point, and we can add one more feature, we can change the size dynamically.

@tradeJmark 2017-07-18 15:19:10

I might argue with you on the point that a multidimensional array is a different "type" of array. It's simply a term used to describe an array that happens to contain other arrays. Both the outer arrays and the inner arrays (and those in between, if they exist) are just regular arrays.

@TreyMcGowan 2015-11-19 17:43:49

int[] SingleDimensionalArray = new int[2]

int[][] MultiDimensionalArray = new int[3][4]

@Bono 2015-11-19 19:24:16

While this code may answer the question, it would be better to explain how it solves the problem without introducing others and why to use it. Code-only answers are not useful in the long run.

@Khaled.K 2015-10-21 13:39:47

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

@HyperNeutrino 2015-05-23 19:56:19

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]

@Muhammad Suleman 2015-01-20 11:54:02

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 ); 

@Nate 2009-07-29 14:29:17

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.

@Chet 2009-07-29 14:31:04

I agree on that point. The type of the variable is not "TYPE", but actually a TYPE[], so it makes sense to write it that way for me.

@wener 2014-03-05 12:43:42

Google style suggest this too.

@Jeroen Vannevel 2015-03-19 01:46:01

Note that int[] a, b; will not be the same as int a[], b;, a mistake easy to make if you use the latter form.

@Amit Bhandari 2013-06-04 06:02:49

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];

@Jon Skeet 2015-02-21 23:08:38

There is absolutely no difference between the second and third approaches, other than that the second approach only works when you're also declaring a variable. It's not clear what you mean by "shows the property of anonymous array-object creation" but they really are equivalent pieces of code.

@Jon Skeet 2015-02-21 23:12:24

Also, the first snippet does initialize the array - it is guaranteed to have the value 0 for every array element.

@Chet 2009-07-29 14:29:56

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.

@Cookie Monster 2018-06-28 10:26:01

So it is not necessary to include int[] name = new int[5] ?

@Dave 2009-07-29 15:56:20

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" );

@CyprUS 2015-08-27 00:05:03

what is the "<>" called in the list that you created ?

@Thomas Owens 2009-07-29 14:25:31

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).

@Anti Earth 2012-10-03 04:20:25

What is the standard for which to use? I've only just discovered the former, and I find it horrifically misleading :|

@Celeritas 2013-08-09 04:50:59

For what it's worth my prof said that the second way is more typical in Java and that it better conveys what is going on; as an array related to the type the variable was cast as.

@Muhammad Suleman 2015-05-05 11:17:28

For a side note: A language having more than one semantics for declaring one thing meaning bad language design.

Related Questions

Sponsored Content

21 Answered Questions

69 Answered Questions

[SOLVED] How do I remove a particular element from an array in JavaScript?

  • 2011-04-23 22:17:18
  • Walker
  • 5130608 View
  • 6428 Score
  • 69 Answer
  • Tags:   javascript arrays

42 Answered Questions

[SOLVED] How do I check if an array includes an object in JavaScript?

28 Answered Questions

[SOLVED] For-each over an array in JavaScript?

38 Answered Questions

[SOLVED] Loop through an array in JavaScript

77 Answered Questions

[SOLVED] Is Java "pass-by-reference" or "pass-by-value"?

31 Answered Questions

[SOLVED] How to append something to an array?

32 Answered Questions

[SOLVED] Create ArrayList from array

18 Answered Questions

[SOLVED] How do I empty an array in JavaScript?

  • 2009-08-05 09:08:39
  • amir
  • 1970106 View
  • 2199 Score
  • 18 Answer
  • Tags:   javascript arrays

8 Answered Questions

[SOLVED] Why is subtracting these two times (in 1927) giving a strange result?

  • 2011-07-27 08:15:58
  • Freewind
  • 565188 View
  • 6142 Score
  • 8 Answer
  • Tags:   java date timezone

Sponsored Content