9.2 Declaring and Initializing Arrays

Chapter Table of Contents

Ch. 9 Arrays

Section Table of Contents

Here is an array of integers. It is one dimensional and only has rows. Below are 2 different ways to declare and initialize the same array. Notice that the keyword new is being used in the first way to initialize an array, signifying that arrays are objects.

// declare and initialize array with length
int[] a = new int[3];
a[0] = 97; // assign elements manually
a[1] = 62;
a[2] = 85;

// declare and initialize array with elements (identical to a)
int[] b = {97, 62, 85}

Notice that to declare a one dimensional int array, you use the syntax int[]. Similarly, to declare a one dimensional String array, you use String[]. This pattern is the same for all data types.

For the first initialization method, the number that goes with the square brackets [ ] is the length of the array. The length of an array is fixed and cannot be changed. Later you will learn about lists, which are dynamic and can change their size.

If you initialize an array in this way, the array will be filled with default values. For example, an int array declared in the method above will produce the array {0, 0, 0}. If you want to change these values, you will need to do so manually by assigning a new element to each index/position in the array in the following way:

nameOfArray[index] = element;

In the second initialization method, the array’s elements are already given. Be sure to separate elements with a comma.


Copyright © 2021 Code 4 Tomorrow. All rights reserved. The code in this course is licensed under the MIT License. If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.