Java Reference
In-Depth Information
sequence of values of type double , so you use the type double[] . Thus, you can
declare a variable for storing your array as follows:
double[] temperature;
Arrays are objects, which means that they must be constructed. Simply declaring a
variable isn't enough to bring the object into existence. In this case you want an array
of three double values, which you can construct as follows:
double[] temperature = new double[3];
This is a slightly different syntax than you've used previously to create a new
object. It is a special syntax for arrays only. Notice that on the left-hand side you don't
put anything inside the square brackets, because you're describing a type. The variable
temperature can refer to any array of double values, no matter how many elements
it has. On the right-hand side, however, you have to mention a specific number of ele-
ments because you are asking Java to construct an actual array object and it needs to
know how many elements to include.
The general syntax for declaring and constructing an array is as follows:
<element type>[] <name> = new <element type>[<length>];
You can use any type as the element type, although the left and right sides of this
statement have to match. For example, any of the following lines of code would be
legal ways to construct an array:
int[] numbers = new int[10]; // an array of 10 ints
char[] letters = new char[20]; // an array of 20 chars
boolean[] flags = new boolean[5]; // an array of 5 booleans
String[] names = new String[100]; // an array of 100 Strings
Color[] colors = new Color[50]; // an array of 50 Colors
Some special rules apply when you construct an array of objects such as an array
of String s or an array of Color s, but we'll discuss those later in the chapter.
When it executes the line of code to construct the array of temperatures, Java will
construct an array of three double values, and the variable temperature will refer
to the array:
[0]
[1]
[2]
temperature
0.0
0.0
0.0
As you can see, the variable temperature is not itself the array. Instead, it stores
a reference to the array. The array indexes are indicated in square brackets. To refer to
an individual element of the array, you combine the name of the variable that refers
 
Search WWH ::




Custom Search