When an array is created, its elements are given default initial values of for primitive types and null for reference types. Array elements can be given user -defined initial values when the array is declared. The initial values, separated by commas, are placed in braces in place of the new variable_type[size] syntax. The number of initial values provided determines the size of the array. For example, to create and initialize a four-element 1-D integer array, you might use int[] intArray = {11, 18, 3, 42}; The zeroth (first) element of the array will have an initial value of 11 and so on. The elements of a 2-D array can be initialized with a similar convention except that an extra set of braces is used to denote each row of the array. For instance, to create and initialize a 2-D array of double values, you might use this syntax ” double[][] doubleArray = { {1.0, 5.6, 3.2}, {5.2, 11.2, 0.8} }; This syntax would create a 2-D array with two rows and three columns . The initial value of the [0][0] element would be 1.0 and so on. Floating point literals default to type double . Arrays that store reference type elements can initialize their elements inside braces as well. Example: Initializing Array ElementsLet us add an array of type double to the Air class first described in the "Creating a 1-D Array" example. The moleFr[] array represents the mole fraction of each species in the gas mixture. The sum of the mole fractions for any gas mixture will equal 1. The elements of the moleFr[] array are initialized when the array is declared by placing the initial values inside curly braces. The elements of the species[] array are initially set to null references. They are then assigned values using the Air2 constructor. public class Air2 { private double pressure, temperature; private Species species[] = new Species[2]; private double moleFr[] = { 0.7885, 0.2115 }; public Air2(double p, double t) { pressure = p; temperature = t; species[0] = new Species("N2",0.0280134); species[1] = new Species("O2",0.0319988); } public double getPressure() { return pressure; } public double getTemperature() { return temperature; } } |