Skip to main content
IBM 
ShopSupportDownloads
IBM HomeProductsConsultingIndustriesNewsAbout IBM
IBM : developerWorks : Java : Education - online courses
Java Collections Framework
Download tutorial zip fileView letter-sized PDF fileView A4-sized PDF fileE-mail this tutorial to a friend
Main menuSection menuGive feedback on this tutorialPreviousNext
5. Historical collection classes
  


Arrays page 2 of 7


One learns about arrays fairly early on when learning the Java programming language. Arrays are defined to be fixed-size collections of the same datatype. They are the only collection that supports storing primitive datatypes. Everything else, including arrays, can store objects. When creating an array, you specify both the number and type of object you wish to store. And, over the life of the array, it can neither grow nor store a different type (unless it extends the first type).

To find out the size of an array, you ask its single public instance variable, length, as in array.length.

To access a specific element, either for setting or getting, you place the integer argument within square brackets ([int]), either before or after the array reference variable. The integer index is zero-based, and accessing beyond either end of the array will throw an ArrayIndexOutOfBoundsException at run time. If, however, you use a long variable to access an array index, you'll get a compiler-time error.

Arrays are full-fledged subclasses of java.lang.Object. They can be used with the various Java constructs except for an object:

Object obj = new int[5];
if (obj instanceof int[]) {
  // true
}
if (obj.getClass().isArray()) {
  // true
}

When created, arrays are automatically initialized, either to false for a boolean array , null for an Object array, or the numerical equivalent of 0 for everything else.

To make a copy of an array, perhaps to make it larger, you use the arraycopy() method of System. You need to preallocate the space in the destination array.

System.arraycopy(Object sourceArray, int
        sourceStartPosition, Object destinationArray, int
        destinationStartPosition, int length)

Main menuSection menuGive feedback on this tutorialPreviousNext
PrivacyLegalContact