Skip to content

Arrays

An array in Java is a data structure that allows you to store multiple values of the same type in a single variable. Arrays can store any data type: int, char, String, etc. Arrays in Java are objects and they are dynamically allocated.

Declaring an array

Let's look at the general form of declaring an array:

dataType[] arrayName; //preferred way.

Once an array is declared, you can initialize it. Here is how you can initialize an array in Java:

int[] myArray = new int[10];

In this code, myArray is an array that can hold ten integers. The new keyword allocates memory for ten integers consecutively in memory and returns the reference to the first memory location.

You can also initialize an array with specific values as follows:

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

In this case, the size of the array is determined by the number of values in the curly braces {}.

Accessing Data in an Array

To access the elements of an array, you use the index number that refers to the position of the element in the array. In Java, array indexing starts at 0. For example, to access the first element of the array, you use index 0.

Here's how you can access elements in an array:

int[] myArray = {1, 2, 3, 4, 5};
System.out.println(myArray[0]); // Prints 1
System.out.println(myArray[4]); // Prints 5

You can also change the value of a specific element in an array by accessing it using its index:

myArray[2] = 10; // Changes the third element of the array to 10

Using Arrays with Loops

Loops are often used with arrays to access each element in the array. Here's how you can use a for loop to access and print all the elements in an array:

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

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

In this code, the variable i starts from 0 and increases by 1 in each loop iteration until it becomes equal to the length of the array (myArray.length). This ensures that all the elements of the array are accessed.

Tasks

In a new Java file named Week6Task1.java, complete the following tasks:

  1. Declare an array of strings named colors and initialize it with the values "red", "blue", "green", "yellow", and "purple".
  2. Print the third value in the array.
  3. Change the value of the second element in the array to "black".
  4. Print the entire array to check your changes.
  5. Use a for loop to iterate over the array and print each color.

Remember that arrays in Java are zero-indexed, which means the first element is at index 0.

Answers

Additional Resources

W3 Schools - Java Arrays

Oracle Docs - Arrays