CIS 35A: Introduction to Java Programming

Home | Green Sheet | Lectures | Assignments | FAQ | Grades

Arrays

Arrays
Basic skills
Create

An array is a collection of a fixed number of variables called elements or components, wherein all the elements are of the same data type.

How to create an array

  • An array can store more than one primitive type or object.
  • An element is one of the items in an array.
  • To create an array, you must declare a variable of the correct type and instantiate an array object that the variable refers to.
  • To declare an array variable, you code a set of empty brackets after the type or the variable name.
  • To instantiate an array, you use the new keyword and specify the length, or size, of the array in brackets following the array type.
  • You can specify the array length by coding a literal value or by using a constant or variable of type int.
  • When you instantiate an array of primitive types, numeric types are set to zeros and boolean types to false.
  • When you create an array of objects, they are set to nulls.

The syntax for declaring and instantiating an array

	Two ways to declare an array

		type[] arrayName;
		type arrayName[];

	How to instantiate an array

		arrayName = new type[length];

	How to declare and instantiate an array in one statement

		type[] arrayName = new type[length];

Examples of array declarations

	Code that declares an array of doubles

		double[] prices;

	Code that instantiates an array of doubles

		prices = new double[4];

	Code that declares and instantiates an array of doubles in one statement

		double[] prices = new double[4];

Other examples of array declarations

	An array of String objects

		String[] titles = new String[3];

	An array of Product objects

		Product[] products = new Product[5];

	Code that uses a constant to specify the array length

		final int TITLE_COUNT = 100;      // array size set at compile time
		String[] titles = new String[TITLE_COUNT];

	Code that uses a variable to specify the array length

		int titleCount = 100;     // array size not set until run time
		String[] titles = new String[titleCount];
Previous | Create | Assign | for loops | Enhanced for loops | Next