Indexing and Modifying Elements

Part of: Array

Accessing Elements by Index. Each slot in an array has an index , its position number. Java arrays are zero-indexed : the first element is at index 0, the second at index 1, and so on. If an array has length n, the valid indices run from 0 to n - 1. The last element is always a[a.length - 1]. Reading vs. Writing. The same a[i] notation both reads and writes: - Read: int x = a[2]; copies the value at index 2 into x. - Write: a[2] = 99; stores 99 into index 2, replacing whatever was there. Indices Can Be Expressions. An index does not have to be a literal number. Any int expression works, which is what makes loops useful: Swapping Two Elements. A common pattern is swapping. You must use a temporary variable, or the first assignment overwrites the value you still need: What usually goes wrong. What you see What caused it How to fix it --- --- --- ArrayIndexOutOfBoundsException: Index 4 out of bounds for length 4 The code read a[a.length], one slot past the end The last valid index is a.length - 1 Both slots hold the same value after a swap The first assignment overwrote the value the second assignment still needed Copy one value into a temporary variable before overwriting The array i

Challenge: Swap First and Last