I was trying to learn the array fundamentals in Java and this question arises:
Version 1:
int[] x = {12,34,56,78};
Version 2:
int[] x;
x = {12,34,56,78};
Version 1 is correct but version 2 is incorrect.
Why is this the case? What is the story behind it?
Please, describe this from a compiler-oriented point of view.
int x[] = {12,34,56,78};
In this case the compiler knows that it needs storage for four integers; this is comparable to saying int x[4]
.
int x[];
/* ... */
x = {12,34,56,78};
However, in this case the compiler sees int x[]
and knows it must allocate space for an array but it doesn't know how much until it gets to the following line, at which time it is too late.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With