Skip to content

Commit 8f85fa7

Browse files
authored
Cleanup concepts arrays, for-loops and foreach-loops (exercism#2000)
Update: * array concept documentation and add blurb * Update for-loops concept docs and blurb * Update the for-each loop docs and blurb * Apply suggestions from code review * Co-authored-by: KOTP <keeperotphones@gmail.com> Add: * trailing newlines back to config.json * Co-authored-by: KOTP <keeperotphones@gmail.com>
1 parent a624e32 commit 8f85fa7

File tree

10 files changed

+236
-176
lines changed

10 files changed

+236
-176
lines changed

concepts/arrays/.meta/config.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
{
2-
"blurb": "TODO: add blurb for arrays concept",
2+
"blurb": "Arrays are fixed-size collections of elements with the same type.",
33
"authors": [
44
"samuelteixeiras",
55
"ystromm"

concepts/arrays/about.md

Lines changed: 42 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -1,37 +1,65 @@
1-
# About
1+
# About Arrays
22

3-
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:
49

510
```java
6-
// Declare array with explicit size (size is 2)
7-
int[] twoInts = new int[2];
11+
type[] variableName = new type[size];
12+
```
813

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`).
1115

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`).
1418

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 = new int[2];
1722
```
1823

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:
2025

2126
```java
2227
// Two equivalent ways to declare and initialize an array (size is 3)
2328
int[] threeIntsV1 = new int[] { 4, 9, 7 };
2429
int[] threeIntsV2 = { 4, 9, 7 };
2530
```
2631

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.
2833

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:
3058

3159
```java
3260
char[] vowels = { 'a', 'e', 'i', 'o', 'u' };
3361

34-
for(char vowel:vowels) {
62+
for(char vowel: vowels) {
3563
// Output the vowel
3664
System.out.print(vowel);
3765
}
@@ -51,34 +79,3 @@ for (int i = 0; i < 3; i++) {
5179

5280
// => aei
5381
```
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.
83-
84-
[multi-dimensional-arrays] https://www.programiz.com/java-programming/multidimensional-array

concepts/arrays/introduction.md

Lines changed: 41 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,34 +1,65 @@
1-
# Introduction
1+
# Introduction to Arrays
22

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 = new type[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`).
418

519
```java
620
// Declare array with explicit size (size is 2)
721
int[] twoInts = new int[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 = new int[] { 4, 9, 7 };
29+
int[] threeIntsV2 = { 4, 9, 7 };
30+
```
831

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
937
// Assign second element by index
1038
twoInts[1] = 8;
1139

1240
// Retrieve the second element by index and assign to the int element
13-
int element = twoInts[1];
41+
int secondElement = twoInts[1];
1442
```
1543

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:
1748

1849
```java
19-
// Two equivalent ways to declare and initialize an array (size is 3)
20-
int[] threeIntsV1 = new int[] { 4, 9, 7 };
21-
int[] threeIntsV2 = { 4, 9, 7 };
50+
int arrayLength = someArray.length;
2251
```
2352

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.
2556

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:
2758

2859
```java
2960
char[] vowels = { 'a', 'e', 'i', 'o', 'u' };
3061

31-
for(char vowel:vowels) {
62+
for(char vowel: vowels) {
3263
// Output the vowel
3364
System.out.print(vowel);
3465
}

concepts/arrays/links.json

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,10 @@
11
[
2+
{
3+
"url": "https://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html",
4+
"description": "arrays"
5+
},
26
{
37
"url": "https://www.programiz.com/java-programming/multidimensional-array",
48
"description": "multi-dimensional-arrays"
59
}
6-
]
10+
]

concepts/for-loops/.meta/config.json

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,8 @@
11
{
2-
"blurb": "TODO: add blurb for for-loops concept",
2+
"blurb": "For loops allow for iteration over a specified range.",
33
"authors": [
44
"samuelteixeiras",
55
"ystromm"
66
],
7-
"contributors": [
8-
]
7+
"contributors": []
98
}

concepts/for-loops/about.md

Lines changed: 34 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1,61 +1,67 @@
1-
# About
1+
# About For Loops
22

3-
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.
44
The loop consists of four parts:
55

66
```java
7-
for (initialization; test; update)
8-
{
9-
// body
7+
for (initialization; test; update) {
8+
body;
109
}
1110
```
1211

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.
1514
For example:
1615

1716
```java
18-
int i=1
17+
int i = 1
1918
```
2019

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:
2825

2926
```java
3027
i <= 10
3128
```
3229

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:
3533

3634
```java
3735
i++
3836
```
3937

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:
4139

4240
```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);
4843
}
4944

50-
// => aeiou
45+
/* =>
46+
1
47+
4
48+
9
49+
16
50+
*/
5151
```
5252

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:
5462

5563
- You can start or stop at the index you want.
5664
- You can use any (boolean) termination condition you want.
5765
- You can skip elements by customizing the incrementing of the loop variable.
5866
- You can process collections from back to front by counting down.
59-
- You can use `for` loops in scenarios that don't involve collections.
60-
61-
[for-loop]: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html
67+
- You can use `for` loops in scenarios that do not involve collections.

0 commit comments

Comments
 (0)