In the following short programs, you can see the workings of an array.
public class Myaray
{
public static void main(String[]
args)
{
int[] array1 =
{7,4,8,1,4,1,4};
int[]array2 =
new int[array1.length];
System.out.println("array1:
[");
for (int i = 0; i
< array1.length; i++)
{
System.out.print(array1[i] + "
");
}
System.out.println("]");
array2[0]= 0;
array2[1]= 1;
array2[2]= 2;
array2[3]= 3;
array2[4]= 4;
array2[5]= 5;
array2[6]= 6;
System.out.println("array2: [");
for (int i = 0; i
< array2.length; i++)
{
System.out.print(array2[i] + "
");
}
}
}
Output:
array1: [
7 4 8 1 4 1 4 ]
array2: [
0 1 2 3 4 5 6
Program Description:
This program has a public static void main as all Java™ programs do.
Once inside the main, we define two integer arrays. We then have a for
loop that loops through the array, reading all its elements and printing
them out with a System.out.println.
Next, we load the second array with numbers. Note that we start
indexing the array with the number zero. Zero is always the first element
in an array.
Finally, when we have loaded the array, we do another for loop and
print out the elements we just loaded.
What happens if you add too many elements to the array?
public class Myaray
{
public static void
main(String[] args)
{
int[] array1 = {7,4,8,1,4,1,4};
int[]array2 = new int[array1.length];
System.out.println("array1: [");
for ( int i = 0; i < array1.length; i++)
{
System.out.print(array1[i] + " ");
}
System.out.println("]");
array2[0]= 0;
array2[1]= 1;
array2[2]= 2;
array2[3]= 3;
array2[4]= 4;
array2[5]= 5;
array2[6]= 6;
array2[7]= 7; Too many elements in the array!
System.out.println("array2: [");
for ( int i = 0; i <
array2.length; i++)
{
System.out.print(array2[i] + " ");
}
}
}
Output:
java.lang.ArrayIndexOutOfBoundsException: 7
at Myaray.main(Myaray.java:37)
Exception in thread "main" array1: [
7 4 8 1 4 1 4 ]
Summary:
- Array elements start with index of zero and not one.
- If you put too many elements in an array, it will throw an
ArrayIndexOutOfBoundsException.
- You can populate an array at that time you define it: int[]
array1 = {7,4,8,1,4,1,4} or you can load it an element at a time:
array2[0]= 0;
- You can create an array using another array as a pattern:
int[]array2 = new int[array1.length];
- You can read an array's elements with a for loop. However, this is not
the only way. You can load an array in a similar fashion.
Note! All the above programs have been developed and tested in
WebSphere® Application Developer version 5.1
|