I must have missed this in K&B. the following code is run with the command: java ArrayTest 0 1 2
What I see here is an array of 3 elements being pushed into an array that was defined with 2 elements. Do you agree? This code compiles, runs and prints 012012. Am I reading this correctly? If so does this mean that an array will "auto size" itself to accespt all of the elements of another array being assigned to it? Thanks
In short: s is just a reference-variable of type "String-Array" and as such it can point to String-Arrays of any size. First you let it reference an Array of size 2 and after that to an array of size 3. Ther is nothing like "auto-size" as s denotes just a reference-variable and not an array!
Originally posted by Henry Wong: Just in case the OP was under the impression that the following...
does an element by element assignment, it does not. To do a copy of the elements of the array into another array, you should use the System.arraycopy() method.
Or to put it differently again:
defines an object reference which is able to point at String arrays, and at time of creation it happens to point at an String array object with a dimension of 2. Then the object to which s is pointing is changed by this line:
Now args is a String array as well, and since s was defined to point at String arrays, the assignment is correct (the original String array is likely to be gc-fodder), and the program runs happily.
Dolphins are grey, but they dream in colour.
Yes. The Arrays are not like Collections wherein they are dynamically varying (able to grow/shrink) nature. (Though, the code internally does it explicitly).
As others told, what you are doing here is just making the String reference variable s to point to a * different * array and now its of args, which was previously to the array created through String.
Just reassigning the same variable to point to the * different object *.