[ ^ CSE 341 | section index | <-- previous ]

Arrays

When I said there were two kinds of Java types, I was actually lying. In Java, arrays are a third type that closely resembles objects, except that they have syntactic support (and some special type rules that we won't go into).

Declaring an array in Java creates a reference to an array; you do not actually get an array until you allocate it:

int[] squid; squid[5] = 0; // Runtime error. int[] whale = new int[10]; whale[5] = 0; // OK

When you allocate an array, what you get depends on the element type:

Therefore, you must often allocate each member of an array manually:

Point[] octopus = new Point[10]; for (int i=0; i<octopus.length; i++) octopus[i] = new Point(0, 0);

Wrapper types

As previously noted, primitive types are not Object subclasses. However, some classes (most notably the collection classes) only take Objects as parameters. Therefore, Java provides a wrapper class for each primitive:

int clam = 5; double oyster = 2.3; Vector v = new Vector(); v.add( new Integer(clam) ); v.add( new Double(oyster) ); // bad practice, but legal int oyster = ((Integer)v.elementAt(0)).intValue();

The wrapper classes are defined in the package java.lang. The wrapper classes are also home of several static utility methods to, for example, convert an integer into a string.


Last modified: Wed Apr 19 17:49:47 PDT 2000