Java Reference
In-Depth Information
NOTE
The choice of which style to use is a matter of personal prefer-
ence. The sample programs in this topic place the brackets after
the information type rather than the variable name, which is the
more popular convention among Java programmers.
Creating Array Objects
After you declare the array variable, the next step is to create an array object and assign
it to that variable. To do this:
Use the new operator.
n
Initialize the contents of the array directly.
n
Because arrays are objects in Java, you can use the new operator to create a new instance
of an array, as in the following statement:
String[] players = new String[10];
This statement creates a new array of strings with 10 slots that can contain String
objects. When you create an array object by using new , you must indicate how many
slots the array will hold. This statement does not put actual String objects in the slots;
you must do that later.
4
Array objects can contain primitive types, such as integers or Booleans, just as they can
contain objects:
int[] temps = new int[99];
When you create an array object using new , all its slots automatically are given an initial
value ( 0 for numeric arrays, false for Booleans, '\0' for character arrays, and null for
objects).
The Java keyword null refers to a null object (and can be used for
any object reference). It is not equivalent to zero or the '\0' char-
acter as the NULL constant is in C.
NOTE
Because each object in an array of objects has a null reference when created, you must
assign an object to each array element before using it.
The following example creates an array of three Integer objects and then assigns each
element an object:
Integer[] series = new Integer[3];
series[0] = new Integer(10);
 
Search WWH ::




Custom Search