Java syntax: Subscripted variable
array [ int - expression ]
Examples : b= b + 2;
Purpose : To access an array element, to either retrieve its
value (as in b ) or change it (above, b is changed).
the value 2 in b is called the subscript , or index , of the array element. We call
b a subscripted variable.
The range of an array is the set of values that can be used as indices. The
range of b consists of 0 , 1 , 2 , and 3 ; we write this range as 0..3 .
The following statement stores the sum of b and b in variable b :
b= b + b;
Any int expression can be used as an index. For example, if an int variable
x has the value 5 , b[x - 4] refers to subscripted variable b .
Declarations of arrays
Below, we show a declaration of an array:
int  b;
The notation int  is read as “ int array”, and b 's type is int  . Arrays are
objects. Just as the declaration:
does not create a String object, b 's declaration does not create an array object.
It merely declares that variable b can contain the name of an int array object.
Type int is called the base type of the array. Any type can be used as the
base type. Here is a declaration for an array of strings:
Creating an array
To create an array object and assign it to b , use a new-expression in an assign-
ment statement. The new-expression syntax is slightly different from other new-
expressions; no constructor is called. Here is an example:
b= new int ;
Common error . When using a subscripted variable b[i] , the value of i must be within the range
of b —one of the values in 0..b.length - 1 . If i is not in range, an IndexOut-
OfBoundsException occurs and execution aborts. Get in the habit of always
asking yourself, with each variable b[i] you write, whether i is within range.