While it doesn't matter which location you use for the square brackets in the declaration, it does matter how many pairs of square brackets you place in thetwo locations combined. The number of dimensions on the array (if you want to think of a Java array as having dimensions) will equal the total number of pairs of empty square brackets in the declaration of the reference variable. Thus, in this case, the array is a two-dimensional arraybecause there is one pair of square brackets next to the type and another pair next to the variable name.
This program goes on to use nested for loops to populate the array and then to display the contents of the elements.
I personally don't use this syntax, and I hope that you don't either. However, even if you don't use it, you need to be able to recognize it when usedby others.
This program illustrates the use of the array property named length , whose value always matches the number of elements in the array.
As a Java programmer, you will frequently call methods that will return a reference to an array object of a specified type, but of an unknown length. (See, for example, the method named getEventSetDescriptors that is declared in the interface named BeanInfo .) This program simulates that situation.
The method named returnArray returns a reference to an array of type int having two elements. Although I fixed the size of the array in this example, I could just as easily have used a random number to set adifferent size for the array each time the method is called. Therefore, the doArrays method making the call to the method named returnArray has no way of knowing the size of the array referred to by the reference that it receivesas a return value.
This could be a problem, but Java provides the solution to the problem in the length property belonging to all array objects.
The for loop in the method named doArrays uses the length property of the array to determine how many elements it needs to display. This is a very commonscenario in Java.
You cannot cast an array reference from one primitive type to another primitive type, even if the individual elements in the array are of a type thatcan normally be converted to the new type.
This program attempts to cast a reference to an array of type int and assign it to a reference variable of type double .Normally, a value of type int will be automatically converted to type double whenever there is a need for such a conversion. However, this attempted cast produces the following compiler error under JDK1.3.
Why is this cast not allowed?
I can't give you a firm reason why such a cast is not allowed, but I believe that I have a good idea why. I speculate that this is due to the fact that theactual primitive values are physically stored in the array object, and primitive values of different types require different amounts of storage. For example, the type int requires 32 bits of storage while the type double requires 64 bits of storage.