Java and arrays
To practice examples from this blast, go to:: The arrays in JAVA- examples.
Arrays variables are used when it is necessary to store more data of the same type in memory e.g. int.
Consider the following task: You need to enter grades from n subjects and calculate the maximum.
We reserve memory for the grades data and then use n for a cycle to try to enter n grades(eg n = 5):
Consider the following task: You need to enter grades from n subjects and calculate the maximum.
We reserve memory for the grades data and then use n for a cycle to try to enter n grades(eg n = 5):
int grade, n = 5;
String gradeStr;
for( int i = 0; i < n; i++){
gradeStr=JOptionPane.showInputDialog(“Enter your rate”);
grade=Integer.parseInt(rateStr);
}
However, since the grade only remembers one number, only the last grade will be remembered after exiting the for cycle. The task will not be solved this way. The maximum cannot be further determined, as not all grades are stored. Grades could be remembered if we used a array variable instead of a regular variable, which can store more data of the same type. Let's introduce a series;
int [ ] grades= new int [5];
The name of the array is: grades. The operator [] is an indication that it is a array, while the new operator reserves memory for n integers, because the value in square brackets is actually the dimension of the arrays.
0 | 1 | 2 | 3 | 4 |
grades
The figure shows memory that is reserved for less than 5 elements. The numbers below the array represent the array indices of the array. The first member of the array has index 0, and the last n-1, ie. In this case it is 4. If you want to enter a grade of 5 in the index field 2 (the third field) we have written:
grades[ 2 ] = 5;
Here's what the memory state would look like in this case:
5 | ||||
---|---|---|---|---|
0 | 1 | 2 | 3 | 4 |
grades
Entering grades using the Input dialog, through the for loop would now look like:
int [] grades = new int [5];/*added row*/
for( int i = 0; i < 5; i++){
gradeStr=JOptionPane.showInputDialog(“Enter a grade”);
grades[ i ]=Integer.parseInt(gradeStr);/*changed row */
}
A series of grades would be completed in a row through cycles. In cycle 1, when i = 0, the value entered in the dialog would go to the index field 0, in cycle 2 when i = 1 to the rating[1] , which is the second field in the order, and so on until the end of the sequence . At the end of the for cycle, the memory state would look e.g.
3 | 4 | 5 | 5 | 4 |
---|---|---|---|---|
0 | 1 | 2 | 3 | 4 |
grades
Determining the maximum element of an array
Now that all grades are stored in memory, they could be used to determine Maximum grade.
The maximum grade is determined as follows:
The maximum grade is determined as follows:
int max= grades[0];
First, define an integer variable that will represent the maximum grade and assume that it is equal to the first grade in the sequence, ie. its initial value is its grades[0]. Next, the for command is executed and in each cycle the next grade in order (grades[i]) is accessed. In each cycle, it is checked that the new grade may be higher than the current maximum, and if so, that value becomes the maximum. It looks like this:
for( int i = 0; i < n; i++)
{
if(grades[ i ] > max)
{
max=grades[i];
}
}
{
if(grades[ i ] > max)
{
max=grades[i];
}
}
When the cycle is completed the max variable represents the highest grade. The complete code of this example is given in the figure
Declaring and defining an array
The declaration of a series of 10 integers looks like:
int [ ] A;
Definition of the same array(then the memory for that array is also reserved:
A = new int [10];
This will provide a memory location for 10 integers. If we tried to access the 11th element of the string, the program would interrupt execution at that location due to an error.
The disadvantage of arrays is that when we do not know in advance how many arrays the elements will contain, we have to reserve more places than we expect, just in case. Some of these places are likely to remain unused but will not be interrupted by the program.
The possibility to reserve the number of seats exactly as needed will be solved by the use of collections, but this is a subject of exposure at a higher course.
The disadvantage of arrays is that when we do not know in advance how many arrays the elements will contain, we have to reserve more places than we expect, just in case. Some of these places are likely to remain unused but will not be interrupted by the program.
The possibility to reserve the number of seats exactly as needed will be solved by the use of collections, but this is a subject of exposure at a higher course.
Defining an array with real numbers
One array of real numbers is defined similarly to an integer, with double or float instead of int.
float [ ] B = new float[10];
double [ ] C= new double[10];
Giving value to array members
The elements of an array are accessed by indexes starting from 0. For example, for a series of real numbers of 5 elements, defining and assigning values to the elements would be:
double [] A= new double[5];
niz[0]=1.1;niz[1]=2.0;
niz[2]=2.5;
niz[3]=-1.6;
niz[4]=3.3;
The array would then look like:
1.1 | 2.0 | 2.5 | -1.6 | 3.3 |
---|---|---|---|---|
0 | 1 | 2 | 3 | 4 |
A
Giving value to array members when they are known in advance
If we know in advance the values of the array elements then the initialization of the array is done together with the definition of the array. The previous array is initialized as follows:
double [ ] A= {1.1, 2.0, 2.5, -1.6, 3.3 };
EXAMPLE: Loading an array and determining the positive elements in it:
Task text: Enter value n and then enter n members of an integer array and determine how many positives there are.
Solution: N must be entered first to be able to define a array because n is the dimension of that array:
Solution: N must be entered first to be able to define a array because n is the dimension of that array:
int n;
String nStr;String elemenTofArrayStr;
nStr=JOptionPane.showInputDialog("Enter number of elements in the array");
n=Integer.parseInt(nStr);
You will then reserve memory for a series of integers that will have n elements:
//Defining a series of n elements
int [ ] A= new int[n];
Array elements can now be entered:
//Entering array
for(int i = 0; i < n; i++)
{
elementOfArrayStr=JOptionPane.showInputDialog("Enter "+(i+1)+". element of array");
A[i]=Integer.parseInt(elementOfArrayStr);
}
for(int i = 0; i < n; i++)
{
elementOfArrayStr=JOptionPane.showInputDialog("Enter "+(i+1)+". element of array");
A[i]=Integer.parseInt(elementOfArrayStr);
}
The array is then printed as follows using the for command:
//Printing elements of array
for(int i = 0; i < n; i++)
{
System.out.print(A[i]+" ");
}
for(int i = 0; i < n; i++)
{
System.out.print(A[i]+" ");
}
In the second part, using a for cycle with the same parameters as when loading and printing array elements, we count the elements that are positive:
int nmbOfPositive=0;
for(int i = 0; i < n; i++)
{
if (A[i] > 0)
nmbOfPositive++;
}
for(int i = 0; i < n; i++)
{
if (A[i] > 0)
nmbOfPositive++;
}
The complete code is given in the figure below:
Array and objects
Previous examples have shown the storage of a set of simple data. Arrays can also be made from objects of a particular class. For example. a series of 10 element balls (Ball class) would be:
Ball[ ]balls= new Ball[10];
Here are all the elements of the same type, ie the Ball class. If objects of different types are to be placed in a array, then this can be done by specifying the type in the array that the classes of those objects inherit. For example. If need be e.g. make a number of drawing objects: lines, circles, rectangles and all these classes belong to the same hierarchy of classes ie. inherit the Shape class, the array would look like:
Shape [ ] elements=new Shape[10];
In any case, all classes indirectly inherit the Object class, so it can always be written for a series of mixed-type objects:
Object[ ]elements=new Object[];
See more about class inheritance at: Inheritance of classes