Java Textbook: "the size of an array must be known at compile time"

arrays, compile-time, java, runtime

Solution

It is a very poorly worded paragraph, but if you interpret it loosely, it's correct.

In your example, the size of the array is known at compile time. The size is `size`.

You're interpreting "known at compile time" with "static" or "constant," which is understandable. Of course as we know though, the JVM allocates memory dynamically based on the value of `size`.

The author is probably trying to distinguish between an array and something like an `ArrayList`, where the dimensions don't have to be specified upon initialization.

Problem

I was just skimming through one of my old textbooks and found this passage defining arrays in Java: A one-dimensional array is a structured composite data type made up of a finite, fixedsize collection of ordered homogeneous elements to which there is direct access. Finite indicates that there is a last element. Fixed size means that the size of the array must be known at compile time, but it doesn’t mean that all of the slots in the array must contain meaningful values. I have a basic understanding of arrays and am comfortable using them in every day tasks, but I am very confused by the statement that the size of arrays must be known at compile time. A very simple Java program demonstrates that an array can be instantiated with a variable size at runtime: ``` import java.util.Scanner; public class test { public static void main(String[] args) { Scanner scan = new Scanner(System.in); System.out.print("Enter a number: "); int size = scan.nextInt(); int[] array = new int[size]; System.out.println("You just create an array of size " + array.length); } } ``` This compiles, executes, and reaches the end without error. What gives?

Original source