The declaration of an array does not allocate any storage, it just announces the intention of creating an array. A significant difference to the way C/C++ declares an array is that no size is specified with the identifier. Thus the following will cause a compile time error
Note that arrays have a length field not a length()
method.When you start to use Strings you will use the
string,length method,as in s.length();With an array the
length is a field (or property) not a method.
Java arrays know how big they are, and the language provides protection from accidentally walking off the end of them.
Note that at no point do you need to specify the number of elements in the array. You might get exam questions that ask if the following is correct.
The elements of arrays are always set to default values wherever the array is created
int bl[] = new int[5]; for (int i = 0;i<bl.length;i++)
bl[i] = i;
和 int bl[] = {1,2,3,4,5};同樣可以爲數組正確賦值.但是,與String一樣,用NEW是產傷一個新的對象,而用
int bl[] = {1,2,3,4,5};初始化時候先查找是否有該值存在,如沒有則產生新對象,如果有就引用該已有對象.