Java - Static and Dynamic Array Initialization

后端 未结 3 684
[愿得一人]
[愿得一人] 2021-01-05 20:02

Is it true that every array that is initialized during runtime is dynamic and every array that is initialized during compiling is static?

for example:



        
相关标签:
3条回答
  • 2021-01-05 20:30

    Memory is not allocated at the time of declaration.

    eg: int array[100]; ; -- won't compiles

    its only when new operator is encountered memory is allocated.

    So

    array = new int[100]; ; compiles.

    0 讨论(0)
  • 2021-01-05 20:31

    Yes,The size of an array come to know at compile time only but allocation of memory will happen at runtime. Until you encounter 'new' memory won't be allocated to array.

    0 讨论(0)
  • 2021-01-05 20:32

    The distinction of dynamic and static allocation is ambiguous (it somewhat depends on the language what it means). In the most general sense, static allocation means that some size has been predetermined, maybe at compile time.

    In java, any objects (that includes arrays) are always allocated at runtime. That doesn't necessarily mean it's dynamic, it may still be static in the sense that it can't be changed at runtime. Example:

    public class Test1 {
        public final int[] array1 = new int[10];
    
        public int[] array2 = new int[20];
    
        public void setArray2Size(int size) {
             array2 = new int[size];
        }
    }
    

    The array1 is of size 10, and that can't be changed at runtime. Do note that the final keyword. This lets you assign the "array1" member only once. So you can't assign a different array to this member.

    Now, array2 is not final, so you can at any point assign a different array to it, like the setArray2Size()-method does. If there were no assignment after the initial assignment, array2 would still be static in the sense that it can't be changed (because there is no code to do so), although by declaration changing it is allowed.

    A concrete instance of an array can not be resized ever once created (there is no language element to express resizing an array in java). It is somewhat hard to grasp for beginners, but a variable like array2 is not the array. It's a reference to the array. You can however replace the reference that array2 holds with the reference to another array, as shown for array2 in setArray2Size()-method.

    0 讨论(0)
提交回复
热议问题