Home

How to Use an Array Initializer in Java

|
Updated:  
2017-05-05 14:29:11
|
From The Book:  
Java Essentials For Dummies
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[] = <strong>{1, 4, 2, 0, 2, 1, 4, 3, 0, 2}</strong>;

out.println("Room\tGuests");

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

out.print(roomNum);

out.print("\t");

out.println(guests[roomNum]);

}

}

}

java-7e-array-initializer

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: