1D Arrays
- Create arrays with a literal or with `new`, and access elements by index
- Use `.length` to find the number of elements
- Recall the default values that `new` gives array elements
An array is a fixed row of slots
An array stores a fixed number of values of the same type in numbered slots. You can build one from a literal, int[] nums = {10, 20, 30, 40};, or with new, int[] arr = new int[5];, which makes 5 slots. The size is fixed at creation — an array cannot grow or shrink later.
Indexing is zero-based
Elements are accessed by index in square brackets, starting at 0. For int[] nums = {10, 20, 30, 40}, nums[0] is 10 and nums[2] is 30. The last valid index is length - 1; using an index outside 0 to length - 1 throws an ArrayIndexOutOfBoundsException at runtime.
length and default values
The number of slots is arr.length — a field, with no parentheses (unlike String’s length() method). An array made with new fills its slots with defaults: 0 for int, 0.0 for double, false for boolean, and null for object types. So new int[5] is really {0, 0, 0, 0, 0} until you assign values.
Trace this code: int[] nums = {10, 20, 30, 40}; then System.out.println(nums[2]);
- 1.The array literal fills the slots: index 0 = 10, index 1 = 20, index 2 = 30, index 3 = 40.
- 2.
nums[2]reads the value at index 2. - 3.Index 2 holds 30 (it is the third element, because counting starts at 0).
30 — the element at index 2, which is the third value.What does this print? `int[] nums = {10, 20, 30, 40};` then `System.out.println(nums[2]);`
Arrays use arr.length (a field, no parentheses); Strings use s.length() (a method, with parentheses). Mixing them up is a compile error.
What does this print? `int[] arr = new int[5];` then `System.out.println(arr.length);`
An index runs from 0 to length - 1. To loop over every element, use for (int i = 0; i < arr.length; i++) — note the strict <, which stops correctly at the last valid index.
Answer the 2 checkpoints as you read.
Sign in to save your progress