Java Reference
In-Depth Information
int[] Array1 = new int[12];
// Brackets on type
int Array1[] = new int[12];
// Brackets on name
You should pick whichever style you like best,and stick to it. It is not a
good idea to mix both styles in the same program.
Programmers note:
Java programmers usually prefer to place the brackets after the type.
Accessing array elements
Array elements are accessed by means of the array name and the element's
index. In a Java program that has created and initialized the following data:
int singleVal;
int scores[] = { 10, 12, 8, 13, 19 };
the array scores[] is of int type and contains five elements. The elements are
located at index values 0 to 4. The value of scores[0] is 10,scores[1] = 12,
and so on. You could now store the value located at array index 3 into the
variable named singleVal,as follows:
singleVal = scores[3];
After this statement executes,the variable singleVal and the array ele-
ment scores[3] both store the value 13. By the same token,you can use
the array index to store data into an array. For example,if you want to
change the value of the array element scores[4] to 25 you could code as
follows:
scores[4] = 25;
You can also store a variable into an array element,as follows:
singleVal = 25;
scores[4] = singleVal;
Programmers note:
Accessing arrays into primitive variables requires that the primitive
variable be of the same type as the array. An element of an array of
type int can be read into a variable of int type,and an element of an ar -
ray of type double into a variable of type double. Attempting to access
an array element into a variable of different type usually generates an
error.
Search WWH ::




Custom Search