Java Reference
In-Depth Information
Use the bitwise operators
Apply the ? operator
T his chapter returns to the subject of Java's data types and operators. It discusses arrays,
the String type, the bitwise operators, and the ? ternary operator. It also covers Java's for-
each style for loop. Along the way, command-line arguments are described.
Arrays
An array is a collection of variables of the same type, referred to by a common name. In
Java, arrays can have one or more dimensions, although the one-dimensional array is the
most common. Arrays are used for a variety of purposes because they offer a convenient
means of grouping together related variables. For example, you might use an array to hold
a record of the daily high temperature for a month, a list of stock price averages, or a list of
your collection of programming topics.
The principal advantage of an array is that it organizes data in such a way that it can be
easily manipulated. For example, if you have an array containing the incomes for a selec-
ted group of households, it is easy to compute the average income by cycling through the
array. Also, arrays organize data in such a way that it can be easily sorted.
Although arrays in Java can be used just like arrays in other programming languages,
they have one special attribute: they are implemented as objects. This fact is one reason that
a discussion of arrays was deferred until objects had been introduced. By implementing
arrays as objects, several important advantages are gained, not the least of which is that un-
used arrays can be garbage collected.
One-Dimensional Arrays
A one-dimensional array is a list of related variables. Such lists are common in program-
ming. For example, you might use a one-dimensional array to store the account numbers
of the active users on a network. Another array might be used to store the current batting
averages for a baseball team.
To declare a one-dimensional array, you can use this general form:
type array-name [ ] = new type[size] ;
Here, type declares the element type of the array. (The element type is also commonly re-
ferred to as the base type.) The element type determines the data type of each element con-
Search WWH ::




Custom Search