Reputation: 7124
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?
Upvotes: 6
Views: 3737
Reputation: 36304
The size of an array here is "size". The compiler is not bothered about what might be there in "size". Memory is not allocated during compile time, its allocated during runtime. During compile time variables are not directly checked to get their values. Its only during run time that the compiler sees what is present in "size" and allocates memory.
Upvotes: 0
Reputation: 30310
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.
Upvotes: 3