Array initialisation in java

前端 未结 5 1911
忘掉有多难
忘掉有多难 2020-12-01 23:20

I noticed one could write code like this, which is perfectly normal, by the way:

int arrays[] = {1, 2, 3};
for (int n : arrays)
   System.out.println(n);
         


        
5条回答
  •  醉梦人生
    2020-12-02 00:11

    I think whenever we create a variable , the compiler automatically allocates memory to it.The amount of memory created depends upon the type of compiler which you are using.In the first statement you declare an array with the inputs, compiler automatically create space for the array element present in the array but when you declare the array in for loop it create only 2 byte of each run.

    For ex.

    int x; // create 2 bytes of memory
    

    This space is permanently allocated to int x whether you insert value in this space or not.

    int x = "123"; // This code also take 2 bytes of memory and contain value = 123
    

    Similarly,

    int a[] ={1,2,3} // create 6 byte of space in memory, 2 byte for each integer variable.
    

    On the other hand when you declare the array in for loop without using the new identifier the compiler assume that it is an int variable and create only 2 bytes of memory space and program gives error.

    for (int n : {1, 2, 3}) // create only 2 bytes of memory
    

    So by using the new identifier we allocate a new memory space and insert values which is given in the curly braces.

提交回复
热议问题