Java Reference
In-Depth Information
and null for reference types. When you declare an array of a reference
type, you are really declaring an array of variables of that type. Con-
sider the following code:
Attr[] attrs = new Attr[12];
for (int i = 0; i < attrs.length; i++)
attrs[i] = new Attr(names[i], values[i]);
After the initial new of the array, attrs has a reference to an array of
12 variables that are initialized to null . The Attr objects themselves are
created only when the loop is executed.
You can initialize arrays with comma separated values inside braces fol-
lowing their declaration. The following array declaration creates and ini-
tializes an array:
String[] dangers = { "Lions", "Tigers", "Bears" };
The following code gives the same result:
String[] dangers = new String[3];
dangers[0] = "Lions";
dangers[1] = "Tigers";
dangers[2] = "Bears";
When you initialize an array within its declaration, you don't have to ex-
plicitly create the array using new it is done implicitly for you by the sys-
tem. The length of the array to create is determined by the number of
initialization values given. You can use new explicitly if you prefer, but in
that case you have to omit the array length, because again it is determ-
ined from the initializer list.
 
Search WWH ::




Custom Search