Java Tutorial: "The size of the array must be known at compile time"

I was just looking through one of my old tutorials and found this passage defining arrays in Java:

A one-dimensional array is a structured composite data type, consisting of a finite, fixed set of ordered homogeneous elements that has direct access. The final means that there is the last element. A fixed size means that the size of the array must be known at compile time, but that does not mean that all slots in the array must contain meaningful values.

I have a basic understanding of arrays and am comfortable with everyday tasks, but I'm very confused by the statement that the size of the array must be known at compile time.

A very simple Java program demonstrates that an array can be created 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 compilation, execution and termination without errors.

What gives?

+6
source share
2 answers

This is a very poorly worded paragraph, but if you interpret it freely, it’s correct.

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

You interpret “known at compile time” with “static” or “constant”, which is understandable. Of course, as we know, the JVM allocates memory dynamically based on the size value.

Perhaps the author is trying to distinguish between an array and something like ArrayList , where sizes do not have to be specified during initialization.

+3
source

The size of the array here is "size". The compiler does not worry about what might be in size. Memory is not allocated at compile time, it is allocated at runtime. At compile time, variables are not checked directly to get their values. Its only at runtime that the compiler sees what is present in the "size" and allocates memory.

0
source

Source: https://habr.com/ru/post/958820/


All Articles