How to Use an Array Initializer in Java - dummies

How to Use an Array Initializer in Java

By Barry A. Burd

You have a couple options for filling an array in Java. One way is with an array initializer. When you use an array initializer, you don’t even have to tell the computer how many components the array has. The computer figures this out for you.

That bold doodad is an array initializer.

Here’s an example for using an array initializer.

import static java.lang.System.out;

public class ShowGuests {

public static void main(String args[]) {

int guests[] = {1, 4, 2, 0, 2, 1, 4, 3, 0, 2};


for (int roomNum = 0; roomNum < 10; roomNum++) {








An array initializer can contain expressions as well as literals. In plain English, this means that you can put all kinds of things between the commas in the initializer. For instance, an initializer like {1 + 3, keyboard.nextInt(), 2, 0, 2, 1, 4, 3, 0, 2} works just fine.