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
int num[5];
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.
int k=new int[5] {0,1,2,3,4} //Wrong, will not compile!
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};初始化时候先查找是否有该值存在,如没有则产生新对象,如果有就引用该已有对象.