Arrays

Programming Languages · Java Loops & Arrays · 12 min

Keep many values in one array, read and change them, and loop over them.

Making an array

An array holds many values of the same type, in order. Put [] after the type and the values in curly braces. Read one item with its position (its index), starting at 0.

int[] scores = {90, 75, 60};
System.out.println(scores[0]); // 90
  • Create a String[] called colors holding "red", "green" and "blue".

  • Print the first color.

How long is it?

.length tells you how many items an array has. No brackets this time: for arrays it's length, for Strings it's length().

The last item sits at length - 1, because counting starts at 0.

int[] a = {5, 6, 7};
a.length;     // 3
a[a.length - 1]; // 7
  • Print how many items nums has.

  • Print the last item using nums.length - 1.

Changing an item

Put a new value at a position with =, just like a variable. The array keeps its size; only that one slot changes.

String[] menu = {"tea", "cake"};
menu[1] = "pie"; // now tea, pie
  • Put "Ada" in the middle seat (index 1), then print seats[1].

Looping over an array

To visit every item by its index, loop i from 0 up to (but not including) length. Then prices[i] is the item for this round.

for (int i = 0; i < prices.length; i++) {
    // prices[i] is one item
}
  • Use a for loop with prices.length to print every price.

Printing a whole array

Printing an array directly shows gibberish like [I@1b6d3586. The Arrays toolbox fixes that. Bring it in with an import at the very top of the file, then use Arrays.toString(). It can also sort with Arrays.sort().

import java.util.Arrays;
// ...
System.out.println(Arrays.toString(a));
  • Replace the comment at the top with import java.util.Arrays; and print Arrays.toString(nums).

  • Then sort it with Arrays.sort(nums) and print it again the same way.

Put it together: test scores

You have four test scores. Use loops to work out the total and the highest score.

For the highest: start with the first score, then look at each one and keep it if it's bigger.

  • Use a loop to add up every score, then print "Total: " + total.

  • Use a loop and an if to find the highest score, then print "Highest: " + highest.

More in Java Loops & Arrays

Previous: Loops · Next: Methods