Arrays

A fixed-size row of values on the heap. Create arrays two ways, fill them with an index, and loop over them with length.

Java · beginner · 8 min · 20 steps · free

What you'll learn

ArraysDemo.java

public class ArraysDemo {
    public static void main(String[] args) {
        int[] marks = new int[4];
        marks[0] = 70;
        marks[1] = 85;
        int[] bonus = {5, 5, 5, 5};
        int total = 0;
        for (int i = 0; i < marks.length; i++) {
            marks[i] = marks[i] + bonus[i];
            total += marks[i];
        }
        System.out.println("Total: " + total + ", length: " + marks.length);
    }
}

Step by step

  1. new int[4] makes an array of four ints on the heap, all starting at 0.
  2. Index 0 is the first slot.
  3. In the int[] that marks points to, index 1 changes from 0 to 85.
  4. An array literal: the size comes from the values.
  5. total is created on the stack with the value 0.
  6. marks.length is 4: the loop runs for i = 0, 1, 2, 3.
  7. marks[0] = 70 + 5 = 75.
  8. total = 75.
  9. i changes from 0 to 1.
  10. In the int[] that marks points to, index 1 changes from 85 to 90.
  11. total changes from 75 to 165.
  12. i changes from 1 to 2.
  13. marks[2] was 0, so it becomes 0 + 5 = 5.
  14. total changes from 165 to 170.
  15. i changes from 2 to 3.
  16. In the int[] that marks points to, index 3 changes from 0 to 5.
  17. total changes from 170 to 175.
  18. i goes out of scope and disappears.
  19. It prints Total: 175, length: 4.
  20. Total 175 (75 + 90 + 5 + 5). Arrays are fixed-size, zero-indexed, and know their own length.

Common mistakes

Best practices

Key takeaways

Check yourself

What is new boolean[2][0]?

Answer: false. boolean arrays start as false.

Last valid index of an array of length 5?

Answer: 4. Indexes run 0 to 4.

·

More in Arrays and Text