Principle 9.3.3. EFFECTIVE DESIGN: Symbolic Constants.
Using symbolic constants (final variables) instead of literal values makes the program easier to read and to maintain.
intArr have not been given initial values whereas the elements of realArr have been initialized. Note the use of the integer constant ARRSIZE to store the arrays’ size. By using the constant in this way, we do not have to use the literal value 10 anywhere in the program, thereby making it easier to read and to modify the program. If we want to change the size of the array that the program handles, we can just change the value of ARRSIZE. This is an example of the maintainability principle.
PrintArrays program.| Ints | Reals |
| 0 | 1.1 |
| 0 | 2.2 |
| 0 | 3.3 |
| 0 | 4.4 |
| 0 | 5.5 |
| 0 | 6.6 |
| 0 | 7.7 |
| 0 | 8.8 |
| 0 | 9.9 |
| 0 | 10.1 |
static qualifier throughout the PrintArrays class. This enables us to refer to the array and the other variables from within the main() method. If intArr were not declared static, we would get the compiler error attempt to make static use of a non-static variable.
static is justified mainly as a coding convenience rather than a principle of object-oriented design. The only examples we’ve seen so far in which static elements were a necessary design element were the use of static elements in the Math class —Math.PI and Math.sqrt() — and the use of static final variables in TwoPlayerGame — e.g., TwoPlayerGame.PLAYER_ONE.
1 4 9 16 25 36 49 64 81 100 121 144 169 196 225 256 289 324 361 400 441 484 529 576 625 676 729 784 841 900 961 1024 1089 1156 1225 1296 1369 1444 1521 1600 1681 1764 1849 1936 2025 2116 2209 2304 2401 2500
intArr has 50 storage locations. Storing a value in one of these variables is done by an assignment statement:
intArr[k] = (k+1) * (k+1);
length variable can always be used as a loop bound when iterating through all elements of the array:
for (int k = 0; k < intArr.length; k++)
intArr[k] = (k+1) * (k+1);
length-1. Attempting to refer to intArr[length] would cause an IndexOutOfBoundsException because no such element exists.
doubles and populate it with the square roots of the first 20 integers \(\geq\) 1. [Use Math.sqrt(double).] Then write a loop to display the arrays elements.