πŸ’­ What is it?

Learners believe that the length of an array an only be accessed using a fixed number, rather than using the .length property.

For example, instead of writing:

for (int i = 0; i < values.length; i++) {
	println(values[i]);
}

they may write:

for (int i = 0; i < 5; i++) { // hardcoded length
	println(values[i]);
}

This leads to code that only works correctly as long as the array has exactly the hardcoded length, and breaks otherwise.


πŸ› οΈ Why is it incorrect?

Hardcoding array lengths makes the code fragile and less flexible. If the array changes in size (e.g. because of different initialization or because it’s replaced), the loop may no longer behave correctly and may throw runtime errors such as ArrayIndexOutOfBoundsException.

The correct way to access all elements of an array is the use of the built-in .length property, which always reflects the actual size of the array:

int[] values = { 3, 5, 7, 9 };
for (int i = 0; i < values.length; i++) {
	println(values[i]);
}

This ensures that the loop adjusts automatically, no matter how long the array is.


🧩 Typical errors
  1. Using a fixed number instead of .length:
int[] data = new int[10];
for (int i = 0; i < 10; i++) {
	println(data[i]);
}
  1. Failing to adapt the loop when the array size changes:
//int[] test = { 1, 2, 3 };
int[] test = { 1, 2, 3, 4 };

for (int i = 0; i < 3; i++) {
	println(test[i]);
}

🌱 Origin

This misconception may arise from early examples in which arrays are always shown with a fixed, known size. As a result, learners may develop the belief that the array length must or can be repeated manually. Simplified code examples that use constant values instead of the .length property tend to reinforce this misconception.

In addition, some learners may feel insecure when working with object properties in Processing, particularly when using dot notation like array.length, which may seem unfamiliar or confusing at first.


🧩 Related Exercises
6.2a) Fill
Winter 2024/25

Exercise 6.2a Screenshot

6.2b) Fill Γ  la Fibonacci
Winter 2024/25

Exercise 6.2b Screenshot

6.2c) Fill two arrays
Winter 2024/25

Exercise 6.2c Screenshot

6.2d) Double elements
Winter 2024/25

Exercise 6.2d Screenshot

6.2k) Add neighbors
Winter 2024/25

Exercise 6.2k Screenshot

6.3a) Filter people
Winter 2024/25

Exercise 6.3a Screenshot

6.3b) Many balls
Winter 2024/25

Exercise 6.3b Screenshot

6.3c) Switch off
Winter 2024/25

Exercise 6.3c Screenshot

6.4a) Balls with vectors
Winter 2024/25

Exercise 6.4a Screenshot

6.4b) Teleprompter
Winter 2024/25

Exercise 6.4b Screenshot

6.4c) Flying images
Winter 2024/25

Exercise 6.4c Screenshot

6.6a) Split array
Winter 2024/25

Exercise 6.6a Screenshot

6.6b) Fill array
Winter 2024/25

Exercise 6.6b Screenshot

6.6c) Sum of a two-dimensional array
Winter 2024/25

Exercise 6.6c Screenshot

6.6d) Article table
Winter 2024/25

Exercise 6.6d Screenshot

6.6e) Matrix-Vector Multiplication
Winter 2024/25

Exercise 6.6e Screenshot