Arrays
An array is a special type of object that can hold an ordered collection of elements. The type of the elements of the array is called the base type of the array; the number of elements it holds is a fixed attribute called its length . Java supports arrays of all primitive and reference types.
The basic syntax of arrays looks much like that of C or C++. We
create an array of a specified length and access the elements with
the
index
operator, []. Unlike other languages, however,
arrays in Java are true, first-class objects. An array is an instance
of a special Java array class and has a corresponding type in the
type system. This means that to use an array, as with any other
object, we first declare a variable of the appropriate type and then
use the new operator to create an instance of it.
Array objects differ from other objects in Java in three respects:
Java implicitly creates a special array class for us whenever we declare an arraytype variable. It’s not strictly necessary to know about this process in order to use arrays, but it helps in understanding their structure and their relationship to other objects in Java.
Java lets us use the special
[]operator to access array elements, so that arrays look as we expect. We could implement our own classes that act like arrays, but because Java doesn’t have user-defined operator overloading, we would have to settle for having methods likeget( )andput( )instead of using the special[]notation.Java provides a corresponding ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access