Initializing Arrays

Contact Us or call 1-877-932-8228
Initializing Arrays

Initializing Arrays

An array can be initialized when it is created

The notation looks like this:

String[] names = { "Joe", "Jane", "Herkimer" };


String[] names = new String[] {"Joe", "Jane", "Herkimer" };

This automatically creates an array of length 3, because there were 3 items supplied.

int[] nums = new int[] { 2, 4, 6, 8, 10, 12 };

This array will have a length of 6.

If a new array is being assigned to an existing variable, you cannot use the shorter variant, you must use the new keyword and the data type:

String[] names;
names = new String[] {"Joe", "Jane", "Herkimer" };

An array of objects in memory

For arrays of other types of objects:

Book[] titles;
titles = new Book[] { 
	new Book(5011,"Fishing Explained"), 
	new Book(1234, "Help is on the Way")