Java Reference
In-Depth Information
Table 15-3. Class Name of Arrays
Array Type
Class Name
byte[]
[B
short[]
[S
int[]
[I
long[]
[J
char[]
[C
float[]
[F
double[]
[D
boolean[]
[Z
com.jdojo.Person[]
[Lcom.jdojo.Person;
The class names of arrays are not available at compile time for declaring or creating them. You must use the
syntax described in this chapter to create an array. That is, you cannot write the following to create an int array:
[I myIntArray;
Rather, you must write the following to create an int array:
int[] myIntArray;
Array Assignment Compatibility
The data type of each element of an array is the same as the data type of the array. For example, each element of an
int[] array is an int ; each element of a String[] array is a String . The value assigned to an element of an array must
be assignment-compatible to its data type. For example, it is allowed to assign a byte value to an element of an int
array, because byte is assignment compatible to int . However, it is not allowed to assign a float value to an element
of an int array, because float is not assignment compatible to int .
byte bValue = 10;
float fValue = 10.5f;
int[] sequence = new int[10];
sequence[0] = bValue; // Ok
sequence[1] = fValue; // A compile-time error
The same rule must be followed when dealing with a reference type array. If there is a reference type array of type
T , its elements can be assigned an object reference of type S , if and only if, S is assignment compatible to T . The subclass
object reference is always assignment compatible to the superclass reference variable. Because the Object class is the
superclass of all classes in Java, you can use an array of Object class to store objects of any class. For example,
Object[] genericArray = new Object[4];
genericArray[0] = new String("Hello"); // Ok
genericArray[1] = new Person("Daniel"); // Ok. Assuming Person class exists
genericArray[2] = new Account(189); // Ok. Assuming Account class exist
genericArray[3] = null; // Ok. null can be assigned to any reference type
 
Search WWH ::




Custom Search