|
| 1 | +In Java, data structures that can hold zero or more elements are known as _collections_. An **array** is a collection that has a fixed size/length and whose elements must all be of the same type. Elements can be assigned to an array or retrieved from it using an index. Java arrays are zero-based, meaning that the first element's index is always zero: |
| 2 | + |
| 3 | +```java |
| 4 | +// Declare array with explicit size (size is 2) |
| 5 | +int[] twoInts = new int[2]; |
| 6 | + |
| 7 | +// Assign second element by index |
| 8 | +twoInts[1] = 8; |
| 9 | + |
| 10 | +// Retrieve the second element by index and assign to the int element |
| 11 | +int element = twoInts[1]; |
| 12 | +``` |
| 13 | + |
| 14 | +Arrays can also be defined using a shortcut notation that allows you to both create the array and set its value. As the compiler can now tell how many elements the array will have, the length can be omitted: |
| 15 | + |
| 16 | +```java |
| 17 | +// Two equivalent ways to declare and initialize an array (size is 3) |
| 18 | +int[] threeIntsV1 = new int[] { 4, 9, 7 }; |
| 19 | +int[] threeIntsV2 = { 4, 9, 7 }; |
| 20 | +``` |
| 21 | + |
| 22 | +Arrays can be manipulated by either calling an array instance's methods or properties, or by using the static methods defined in the `Array` class. |
| 23 | + |
| 24 | +The fact that an array is also a _collection_ means that, besides accessing values by index, you can iterate over _all_ its values using a `foreach` loop: |
| 25 | + |
| 26 | +```java |
| 27 | +char[] vowels = { 'a', 'e', 'i', 'o', 'u' }; |
| 28 | + |
| 29 | +for(char vowel:vowels) { |
| 30 | + // Output the vowel |
| 31 | + System.out.print(vowel); |
| 32 | +} |
| 33 | + |
| 34 | +// => aeiou |
| 35 | +``` |
| 36 | + |
| 37 | +If you want more control over which values to iterate over, a `for` loop can be used: |
| 38 | + |
| 39 | +```java |
| 40 | +char[] vowels = { 'a', 'e', 'i', 'o', 'u' }; |
| 41 | + |
| 42 | +for (int i = 0; i < 3; i++) { |
| 43 | + // Output the vowel |
| 44 | + System.out.print(vowels[i]); |
| 45 | +} |
| 46 | + |
| 47 | +// => aei |
| 48 | +``` |
0 commit comments