One-Dimensional Arrays


There are two acceptable syntaxes for creating a 1-D array. In the first, square brackets are placed after the array name .

 variable_type array_name[] = new variable_type[size]; 

The second acceptable syntax is to place the square brackets after the variable type.

 variable_type[] array_name = new variable_type[size]; 

As with objects, the two parts of the array creation syntax may be placed on separate lines.

 variable_type array_name[]; array_name = new variable_type[size]; 

When an array is created, its elements are given default values, 0 for primitive type elements and null for reference type elements. You can assign your own initial values to the array elements when the array is declared.

Example: Creating a 1-D array

In this example, we will write an Air class that encapsulates a gas mixture of air. The Air class declares two double type variables that represent the pressure and temperature of the gas. The class also declares a 1-D array of Species objects that represent the primary species in low temperature air (O2 and N2).

When you create an array of reference type variables, of type Species in this example, the array elements are initially null references. You have to initialize each element of the array, in this case by invoking a constructor.

 public class Air {   private double pressure, temperature;   private Species species[] = new Species[2];   //  The constructor initializes each element   //  of the species[] array   public Species(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;   }   public Species getSpecies(int i) {     return species[i];   } } 

The code listing for the Species class is ”

 public class Species {   private String name;   private double molarMass;   public Species(String name, double molarMass) {     this.name = name;     this.molarMass = molarMass;   }   public String getName() {     return name;   }   public double getMolarMass() {     return molarMass;   } } 


Technical Java. Applications for Science and Engineering
Technical Java: Applications for Science and Engineering
ISBN: 0131018159
EAN: 2147483647
Year: 2003
Pages: 281
Authors: Grant Palmer

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net