Skip to content

Latest commit

 

History

History
609 lines (44 loc) · 2.8 KB

File metadata and controls

609 lines (44 loc) · 2.8 KB

ARRAYS IN JAVA

  1. An array is a special type of object that can hold an ordered collection of elements.
  2. The type of the elements of the array is called the base type of the array.
  3. The number of elements it hold is a fixed attribute called its length.
  4. Java supports arrays of all primitive and reference types.
  5. We create an array of a specified length and access the elements with the index operator, []
  6. An array is an instance of a special Java array class and has a corresponding type in the type system. This means that to use an array, as with any other object, we first declare a variable of the appropriate type and then use the new operator to create an instance of it.

ARRAY TYPES

  1. An array type variable is denoted by a base type followed by the empty brackets, [].
int [] arrayOfInts; // preferred
int arrayOfInts []; // C-style
  • In each case, arrayOfInts is declared as an array of integers.
  • The size of the array is not yet an issue because we are declaring only the array type variable.
  • We have not yet created an actual instance of the array class, with its associated storage.
  • It’s not even possible to specify the length of an array when declaring an array type variable.
  • The size is strictly a function of the array object itself, not the reference to it.
// An array of reference types can be created in the same way:
String [] someStrings;
Button [] someButtons;

ARRAY CREATION AND INITIALIZATION

  • The new operator is used to create an instance of an array.
  • After the new operator, we specify the base type of the array and its length with a bracketed integer expression:
arrayOfInts = new int [42];
someStrings = new String [ number + 2 ];
  • We can combine the steps of declaring and allocating the array:
double [] someNumbers = new double [20];
Component [] widgets = new Component [12];
  • Array indices start with ZERO. Thus the first element of someNumbers[] is 0, and the last element is 19.
  • After creation, the array elements are initialized to the default values for their type.
  • For numeric types, this means the elements are initially zero:
int[] grades = new int[30];
grades[0] = 99;
grades[1] = 72;

// grades[2] == 0