W7-Presentation-Java Array
W7-Presentation-Java Array
Introduction to Array
- array is a collection of variables of the same type. It has fixed
number of values and its length is defined upon creation, therefore after
creating an array its length is fixed.
- it can hold multiple same type value at a time, just like a list
of items.
For example, an array of int is a collection of variable of type int and each variable
in the collection has indexed and can hold different int value. Below is the
illustration of a Java array:
Declaring Array
- an array is similar to variable declaration.
- To declare an array, you need to specify the type, followed by
a pair of square brackets and, and then followed by array name or identifier,
for example,
int[] intArray;
or you can put the pair of square brackets after the identifier,
int intArray[];
where type is the data type of the elements; the pair of square brackets are
special symbols that indicates that this variable is an array.
The following are the examples of array declaration in other types:
byte[] byteArray;
short[] shortArray;
long[] longArray;
float[] floatArray;
double[] doubleArray;
boolean[] booleanArray;
char[] charArray;
String[] anArrayOfStrings;
After declaring the array, we can now create it and specify its length. One way
to create an array is with the new keyword. Always remember that the size of an array
is not allowed to be changed once you have created the array. For example,
//array declaration
int[] intArray;
//array creation
intArray = new int[10]
int2DArray[0][1] = 2;
int2DArray[0][2] = 3;
int2DArray[1][0] = 4;
int2DArray[1][1] = 5;
int2DArray[1][2] = 6;
Another way to assign the above values in a multidimensional array is:
int2DArray[0][0]: 1
int2DArray[0][1]: 2
int2DArray[0][2]: 3
On the second outer loop iteration the value of i will become 1 and the value
of j is also 0 to 2, and we will have an output of :
int2DArray[1][0]: 4
int2DArray[1][1]: 5
int2DArray[1][2]: 6
Now, on the last outer loop iteration the value of i will become 2 and the value of j
is again 0 to 2, and we will have an output of :
int2DArray[2][0]: 7
int2DArray[2][1]: 8
int2DArray[2][2]: 9
The same process will be applied on the other nested loop and we
can get this output:
string2DArray[0][0]: a
string2DArray[0][1]: b
string2DArray[0][2]: c
string2DArray[1][0]: d
string2DArray[1][1]: e
string2DArray[1][2]: f