Java Lab Documentation

1D Array

Category:Data Structures

A one-dimensional array is a useful data structure to store multiple elements that can be referenced using one variable. You can access each element in the array using an index. You typically use a 1D array when you know the number of elements you want to store.

Declaring and Initializing a 1D Array

You are able to declare and initialize a 1D array in Java in two different ways:

  • use the new keyword: int arr[] = new int[4];

  • use an initializer list: int arr[] = { 1, 2, 3, 4 };

Examples

Modifying Elements in Array

int[] sampleArray = new int[4];

sampleArray[2] = 4;

Traversing a 1D Array with a for Loop

int[] numbers = {1, 2, 3, 4, 5, 6};

for(int index = 0; index < numbers.length; index++) {
   System.out.println(numbers[index]);
}

Output:

1

2

3

4

5

6

Traversing a 1D Array with a while Loop

int[] numbers = {1, 2, 3, 4, 5, 6};

int index = 0;  // declare the variable that will increment through the loop

while(index < numbers.length) {
   System.out.println(numbers[index]);
   index++;
}

Output:

1

2

3

4

5

6

Traversing a 1D Array with an Enhanced for Loop

int numbers[] = {1, 2, 3, 4, 5, 6};

for (int value : numbers) {
   System.out.println(value);
}

Output:

1

2

3

4

5

6