Everyday Computing Advanced Computing The Internet At Home Health, Mind & Body Making & Managing Money Sports & Leisure Travel Beyond The Classroom
Certification
Databases
Networking
Programming
Moms, Dads, and Grads -- Win $500!
Java All-In-One Desk Reference For Dummies, 2nd Edition

Understanding Arrays in Java


Adapted From: Java All-In-One Desk Reference For Dummies, 2nd Edition

An array is a set of variables that are referenced using a single variable name combined with an index number. Each item of an array is called an element. All the elements in an array must be of the same type. Thus the array itself has a type that specifies what kind of elements it can contain.

The index number is written after the variable name and enclosed in brackets. So, if the variable name is x, you could access a specific element with an expression like x[5].

You might think x[5] would refer to the fifth element in the array. But index numbers start with zero for the first element, so x[5] actually refers to the sixth element. This little detail is one of the chief causes of problems when working with arrays — especially if you cut your array-programming teeth in a language in which arrays are indexed from 1 instead of 0.

The real power of arrays comes from the simple fact that you can use a variable or even a complete expression as an array index. So (for example) instead of coding x[5] to refer to a specific array element, you can code x[i] to refer to the element indicated by the index variable i.

Here are a few additional tidbits of array information to ponder before you get into the details of creating and using arrays:

  • An array is itself an object. You can refer to the array object as a whole rather than a specific element of the array by using the array's variable name without an index. Thus, if x[5] refers to an element of an array, x refers to the array itself.
  • An array has a fixed length that's set when the array is created. This length determines the number of elements that can be stored in the array. The maximum index value you can use with any array is one less than the array's length. Thus, if you create an array of ten elements, you can use index values from 0 to 9.
  • You can't change the length of an array after you create the array.
  • You can access the length of an array by using the length field of the array variable. For example, x.length returns the length of the array x.
Related Articles
Looking at the Architecture of Enterprise JavaBeans
Singling Out Stateless Session Beans in Enterprise JavaBeans
Delving Into the Enterprise JavaBeans Deployment Descriptor
Analyzing Performance in Enterprise JavaBeans
Knowing Why Java and XML Mesh
Related Titles
Java All-In-One Desk Reference For Dummies, 2nd Edition
Java 2 Database Programming For Dummies
Java and XML For Dummies
Jakarta Struts For Dummies
Beginning Programming with Java For Dummies, 2nd Edition