Arrays
Basic skills
Assign
How to assign values to the elements of an array
- To refer to the elements, you use an index that ranges from zero (the first element in the array) to one less than the total number of elements.
- If you specify an index that's less than zero or greater than the upper bound of the array, an ArrayIndexOutOfBoundsException will be thrown.
- You can instantiate an array and provide initial values in a single statement by listing the values in braces. The number of values determines the size of the array.
The syntax for referring to an element of an array
arrayName[index]
The syntax for creating an array and assigning values in one statement
type[] arrayName = {value1, value2, value3, ...};
Code that accesses each element to assign:
values to an array of double types double[] prices = new double[4]; prices[0] = 14.95; prices[1] = 12.95; prices[2] = 11.95; prices[3] = 9.95; //prices[4] = 8.95; // this would throw an ArrayIndexOutOfBoundsException values to an array of String types String[] names = new String[3]; names[0] = "Ted Lewis"; names[1] = "Sue Jones"; names[2] = "Ray Thomas"; objects to an array of Product objects Product[] products = new Product[2]; products[0] = new Product("java"); products[1] = new Product("jsps");
Examples that create arrays and assign values in one statement
double[] prices = {14.95, 12.95, 11.95, 9.95}; String[] names = {"Ted Lewis", "Sue Jones", "Ray Thomas"}; Product[] products = {new Product("java"), new Product("jsps")};