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: Without temp, doing a[0] = a[1]; a[1] = a[0]; would leave both slots equal. Mastering index reads, writes, and swaps is the foundation for every array algorithm to come.
Challenge: Swap First and Last