Java For Dummies, 8th Edition
Book image
Explore Book Buy On Amazon
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.

About This Article

This article is from the book:

About the book author:

Barry Burd, PhD, is a veteran author and educator. At the University of Illinois, he was named five times to the university-wide List of Teachers Ranked as Excellent by their Students. He has written several books on Java and Android development.

This article can be found in the category: