You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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:
3
+
In Java, data structures that can hold zero or more elements are known as _collections_.
4
+
An **array** is a collection that has a fixed size and whose elements must all be of the same type.
5
+
Elements can be assigned to an array or retrieved from it using an index.
6
+
Java arrays use zero-based indexing: the first element's index is 0, the second element's index is 1, etc.
7
+
8
+
Here is the standard syntax for initializing an array:
4
9
5
10
```java
6
-
// Declare array with explicit size (size is 2)
7
-
int[] twoInts =newint[2];
11
+
type[] variableName =newtype[size];
12
+
```
8
13
9
-
// Assign second element by index
10
-
twoInts[1] =8;
14
+
The `type` is the type of elements in the array which can be a primitive type (eg. `int`) or a class (eg. `String`).
11
15
12
-
// Retrieve the second element by index
13
-
int element = twoInts[1];
16
+
The `size` is the number of elements this array will hold (which cannot be changed later).
17
+
After array creation, the elements are initialized to their default values (typically `0`, `false` or `null`).
14
18
15
-
// Check the length of the array
16
-
boolean checkSize = twoInts.length ==2; // => checkSize is true
19
+
```java
20
+
// Declare array with explicit size (size is 2)
21
+
int[] twoInts =newint[2];
17
22
```
18
23
19
-
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:
24
+
Arrays can also be defined using a shortcut notation that allows you to both create the array and set its value:
20
25
21
26
```java
22
27
// Two equivalent ways to declare and initialize an array (size is 3)
23
28
int[] threeIntsV1 =newint[] { 4, 9, 7 };
24
29
int[] threeIntsV2 = { 4, 9, 7 };
25
30
```
26
31
27
-
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.
32
+
As the compiler can now tell how many elements the array will have, the length can be omitted.
28
33
29
-
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:
34
+
Array elements can be assigned and accessed using a bracketed index notation:
35
+
36
+
```java
37
+
// Assign second element by index
38
+
twoInts[1] =8;
39
+
40
+
// Retrieve the second element by index and assign to the int element
41
+
int secondElement = twoInts[1];
42
+
```
43
+
44
+
Accessing an index that is outside of the valid indexes for the array results in an `IndexOutOfBoundsException`.
45
+
46
+
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 (typically only used in generic code).
47
+
The most commonly used property for arrays is its length which can be accessed like this:
48
+
49
+
```java
50
+
int arrayLength = someArray.length;
51
+
```
52
+
53
+
Java also provides a helpful utility class [`java.util.Arrays`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Arrays.html) that has a lot of useful array-related methods (eg. `Arrays.equals`).
54
+
55
+
Java also supports [multi-dimensional arrays](https://www.programiz.com/java-programming/multidimensional-array) like `int[][] arr = new int[3][4];` which can be very useful.
56
+
57
+
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 `for-each` loop:
30
58
31
59
```java
32
60
char[] vowels = { 'a', 'e', 'i', 'o', 'u' };
33
61
34
-
for(char vowel:vowels) {
62
+
for(char vowel:vowels) {
35
63
// Output the vowel
36
64
System.out.print(vowel);
37
65
}
@@ -51,34 +79,3 @@ for (int i = 0; i < 3; i++) {
51
79
52
80
// => aei
53
81
```
54
-
55
-
However, generally a `foreach` loop is preferrable over a `for` loop for the following reasons:
56
-
57
-
- A `foreach` loop is guaranteed to iterate over _all_ values. With a `for` loop, it is easy to miss elements, for example due to an off-by-one error.
58
-
- A `foreach` loop is more _declarative_, your code is communicating _what_ you want it to do, instead of a `for` loop that communicates _how_ you want to do it.
59
-
- A `foreach` loop is foolproof, whereas with `for` loops it is easy to have an off-by-one error.
60
-
- A `foreach` loop works on all collection types, including those that don't support using an indexer to access elements.
61
-
62
-
To guarantee that a `foreach` loop will iterate over _all_ values, the compiler will not allow updating of a collection within a `foreach` loop:
63
-
64
-
```java
65
-
char[] vowels = { 'a', 'e', 'i', 'o', 'u' };
66
-
67
-
for(char vowel:vowels) {
68
-
vowels ='Y'; // This would result in a compiler error
69
-
}
70
-
```
71
-
72
-
A `for` loop does have some advantages over a `foreach` loop:
73
-
74
-
- You can start or stop at the index you want.
75
-
- You can use any (boolean) termination condition you want.
76
-
- You can skip elements by customizing the incrementing of the loop variable.
77
-
- You can process collections from back to front by counting down.
78
-
- You can use `for` loops in scenarios that don't involve collections.
79
-
80
-
Related Topics:
81
-
82
-
- You should be aware that Java supports [multi-dimensional arrays][multi-dimensional-arrays] like `int[][] arr = new int[3][4];` which can be very useful.
Copy file name to clipboardExpand all lines: concepts/arrays/introduction.md
+41-10Lines changed: 41 additions & 10 deletions
Original file line number
Diff line number
Diff line change
@@ -1,34 +1,65 @@
1
-
# Introduction
1
+
# Introduction to Arrays
2
2
3
-
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:
3
+
In Java, data structures that can hold zero or more elements are known as _collections_.
4
+
An **array** is a collection that has a fixed size and whose elements must all be of the same type.
5
+
Elements can be assigned to an array or retrieved from it using an index.
6
+
Java arrays use zero-based indexing: the first element's index is 0, the second element's index is 1, etc.
7
+
8
+
Here is the standard syntax for initializing an array:
9
+
10
+
```java
11
+
type[] variableName =newtype[size];
12
+
```
13
+
14
+
The `type` is the type of elements in the array which may be a primitive type (e.g. `int`) or a class (e.g. `String`).
15
+
16
+
The `size` is the number of elements this array will hold (which cannot be changed later).
17
+
After array creation, the elements are initialized to their default values (typically `0`, `false` or `null`).
4
18
5
19
```java
6
20
// Declare array with explicit size (size is 2)
7
21
int[] twoInts =newint[2];
22
+
```
23
+
24
+
Arrays can also be defined using a shortcut notation that allows you to both create the array and set its value:
25
+
26
+
```java
27
+
// Two equivalent ways to declare and initialize an array (size is 3)
28
+
int[] threeIntsV1 =newint[] { 4, 9, 7 };
29
+
int[] threeIntsV2 = { 4, 9, 7 };
30
+
```
8
31
32
+
As the compiler can now tell how many elements the array will have, the length can be omitted.
33
+
34
+
Array elements may be assigned and accessed using a bracketed index notation:
35
+
36
+
```java
9
37
// Assign second element by index
10
38
twoInts[1] =8;
11
39
12
40
// Retrieve the second element by index and assign to the int element
13
-
intelement= twoInts[1];
41
+
intsecondElement= twoInts[1];
14
42
```
15
43
16
-
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:
44
+
Accessing an index that is outside of the valid indexes for the array results in an `IndexOutOfBoundsException`.
45
+
46
+
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 (typically only used in generic code).
47
+
The most commonly used property for arrays is its length which can be accessed like this:
17
48
18
49
```java
19
-
// Two equivalent ways to declare and initialize an array (size is 3)
20
-
int[] threeIntsV1 =newint[] { 4, 9, 7 };
21
-
int[] threeIntsV2 = { 4, 9, 7 };
50
+
int arrayLength = someArray.length;
22
51
```
23
52
24
-
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.
53
+
Java also provides a helpful utility class [`java.util.Arrays`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Arrays.html) that has lots of useful array-related methods (eg. `Arrays.equals`).
54
+
55
+
Java also supports [multi-dimensional arrays](https://www.programiz.com/java-programming/multidimensional-array) like `int[][] arr = new int[3][4];` which can be very useful.
25
56
26
-
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:
57
+
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 `for-each` loop:
The [for loop][for-loop] provides a mechanism to execute a group of statements repeatedly.
3
+
The [for loop](https://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html) provides a mechanism to execute a group of statements repeatedly until some condition is met.
4
4
The loop consists of four parts:
5
5
6
6
```java
7
-
for (initialization; test; update)
8
-
{
9
-
// body
7
+
for (initialization; test; update) {
8
+
body;
10
9
}
11
10
```
12
11
13
-
The initialization sets an initial state for the loop.
14
-
Typically it declares and sets a variable used in the test expression and update statement.
12
+
The `initialization` sets an initial state for the loop and is executed exactly once at the start of the loop.
13
+
Typically it declares and assigns a variable used in the test expression and update statement.
15
14
For example:
16
15
17
16
```java
18
-
int i=1
17
+
int i=1
19
18
```
20
19
21
-
The test expression tests if the loop should execute the body
22
-
and execute the update statement.
23
-
24
-
If the test evaluates to true the body and the update expression will be executed.
25
-
26
-
If the expression evaluates to false neither the body nor the update statement will be executed and execution continues after the loop.
27
-
An example of a test can be:
20
+
The `test` expression tests if the loop should end.
21
+
If it evaluates to true, the body and then the update expression will be executed.
22
+
If it evaluates to false, neither the body nor the update statement will be executed and execution resumes after the loop's closing bracket.
23
+
Typically it checks the variable assigned in the initialization block.
24
+
For example:
28
25
29
26
```java
30
27
i <=10
31
28
```
32
29
33
-
After executing the loop body, the update expression increments/decrements the loop variable by some value.
34
-
Example:
30
+
After executing the loop body, the `update` expression is executed.
31
+
Typically it increments or decrements the loop variable by some value.
32
+
For example:
35
33
36
34
```java
37
35
i++
38
36
```
39
37
40
-
A for loop executing over each element in an array can look like this:
38
+
A for loop printing out the first four squares would look like this:
41
39
42
40
```java
43
-
char[] vowels = {'a', 'e', 'i', 'o', 'u'};
44
-
45
-
for (int i =0; i<vowels.length; i++) {
46
-
// Output the vowel
47
-
System.out.print(vowels[i]);
41
+
for (int i =1; i <=4; i++) {
42
+
System.out.println(i * i);
48
43
}
49
44
50
-
// => aeiou
45
+
/* =>
46
+
1
47
+
4
48
+
9
49
+
16
50
+
*/
51
51
```
52
52
53
-
A `for` loop does have some advantages over a `foreach` loop:
53
+
If iterating through every element in a collection, a `for-each` loop is preferred, but it can be done with a `for` loop like this:
54
+
55
+
```java
56
+
for (int i =0; i < array.length; i++) {
57
+
System.out.print(array[i]);
58
+
}
59
+
```
60
+
61
+
A `for` loop does have some advantages over a `for-each` loop:
54
62
55
63
- You can start or stop at the index you want.
56
64
- You can use any (boolean) termination condition you want.
57
65
- You can skip elements by customizing the incrementing of the loop variable.
58
66
- You can process collections from back to front by counting down.
59
-
- You can use `for` loops in scenarios that don't involve collections.
0 commit comments