Arrays are objects: type names and ArrayStoreException
An array is a fixed-size, numbered row of values of one type, stored together as a single object on the heap. You reach each value by its index, from 0 to length - 1, in constant time.
Change the code and press Run (Ctrl+Enter). Try to predict the output first, then break it on purpose and read the error. Your edits are saved and match the lesson page.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Write a program that counts how many numbers in {4, -2, 7, 0, -5, 3} are positive, negative and zero.
Write static int indexOf(int[] arr, int target) that returns the first index of target, or -1. Test with {5, 8, 2, 8} and targets 8 and 9.
Write static int[] reversed(int[] arr) that returns a new reversed array, leaving the input unchanged. Print both.
Write a program that shifts every element of {1, 2, 3, 4, 5} one place to the left, moving the first element to the end, giving [2, 3, 4, 5, 1].
Explain it without notes
Why do array indexes start at 0, and what is the valid index range of an array?
What happens in memory when you write int[] b = a;, and how do you make a real copy?
What does System.out.println(arr) print and why? How do you print the contents?
What is array covariance, and what run-time error can it cause?
Expected output
[I
[Ljava.lang.String;
[[I
ArrayStoreException: java.lang.Integer
NegativeArraySizeException: -1