Arrays
Array: Sequence of values of the same type
Construct array: new double[10] //10 is the number of elements, not index.
Store in variable of type double[]
double[] value = new double[10];
When array is created, all values are initialized depending on array type:
Numbers: 0
Boolean: false
Object References: null
There is another way to initialize an array.
int[] squares = {0. 1, 4, 9, 16};
String[] friends = {"Emily", "Bob", "Cindy"};
![]() |
|
Using the value stored:
System.out.println("The value of this data item is " + value[2]);
Get array length as value.length (Not a method!) (It is a final instance variable)
Index values range from 0 to length - 1
Accessing a nonexistent element results in a bounds error
double[] value = new double[10];
value[10] = 29.95; // ERROR
Limitation: Arrays have fixed length
What elements does the data array contain after the following statements?
double[] data = new double[10];
for (int i = 0; i < data.length; i++) data[i] = i * i;
Answer: 0, 1, 4, 9, 16, 25, 36, 49, 64, 81, but not 100
What do the following program segments print? Or, if there is an
error, describe the error and specify whether it is detected at
compile-time or at run-time.
double[] a
= new double[10];
System.out.println(a[0]);
double[] b
= new double[10];
System.out.println(b[10]);
double[]
c;
System.out.println(c[0]);
Answer:
0.
a run-time error: array index out of bounds
a compile-time error: c is not initialized