JAVA :: Arrays
Arrays
Arrays in Java are different than they are in other
languages. Arrays in Java are actual objects that can be passed around and
treated just like other objects. Arrays are a way to store a list of items.
Each element of the array holds an individual item, and you can place items
into and remove items from those slots as you need to. Arrays can contain any
type of value (base types or objects), but you can’t store different types in a
single array. You can have an array of integers, or an array of strings, or an
array of arrays, but you can’t have an array that contains, for example, both
strings and integers.
To create an array in Java, you use three steps:
1. Declare a variable to hold the array.
2. Create a new array object and assign it to the array
variable.
3. Store things in that array.
Declaring Array
Variables
The first step to creating an array is creating a variable
that will hold the array, just as you would any other variable. Array variables
indicate the type of object the array will hold (just as they do for any
variable) and the name of the array, followed by empty brackets ([]). The
following are all typical array variable declarations:
String difficultWords[];
Point hits[];
int temps[];
An alternate method of defining an array variable is to put
the brackets after the type instead of after the variable. They are equivalent,
but this latter form is often much more readable. So, for example, these three
declarations could be written like this:
String[]
difficultWords;
Point[] hits;
int[] temps;
Comments
Post a Comment