Use arrays to store multiple values of the same data type

Arrays 📚

What is an Array?

An array is a collection of multiple values of the same data type stored in a single variable. Think of it as a row of lockers where each locker holds one item of the same type.

Declaring an Array

int[] scores = new int[5];

Here, int[] tells the computer that scores will hold integers, and new int[5] creates space for 5 of them.

Indexing: Accessing Elements

Array indices start at 0. The first element is scores[0], the second scores[1], and so on.

  1. Assign a value: scores[0] = 88;
  2. Retrieve a value: int first = scores[0];

Array Size and Length

The size is fixed once created. Use scores.length to get the number of elements.

int size = scores.length;  // size = 5

Common Operations

  • Loop through an array: for (int i = 0; i < scores.length; i++) { … }
  • Find the maximum: iterate and compare.
  • Calculate the average: sum all elements and divide by scores.length.

Example: Storing Test Scores

Index Score
0 88
1 92
2 76
3 85
4 90

To calculate the average:

int sum = 0;
for (int i = 0; i < scores.length; i++) {
    sum += scores[i];
}
double avg = (double)sum / scores.length;  // avg = 86.6

Analogy: The Array as a Playlist

Imagine an array as a music playlist. Each song (element) is stored in a specific order. You can jump to song number 3 (index 2) and play it instantly.

Exam Tips 📌

  • Remember that array indices start at 0, not 1.
  • Use array.length to avoid IndexOutOfBoundsException.
  • When asked to calculate the sum or average, show the loop and the final formula.
  • For array sorting questions, mention that you can use Arrays.sort(array) or write a simple bubble sort loop.
  • Practice writing code that initialises an array with values directly: int[] nums = {1, 2, 3, 4};

Quick Quiz

  1. What will int[] a = new int[3]; a[0] = 5; print if you output a[0]?
  2. Write a loop that prints all elements of int[] b = {10, 20, 30};.
  3. How many elements can you access in int[] c = new int[10];?

Revision

Log in to practice.

1 views 0 suggestions