4 Arrays — Java Programming
4.1 Introduction
Arrays in Java are similar to arrays of C/C++, and have more capabilities and are more flexible, let us see how.
4.2 Arrays
An array is a collection of similar type of variables that are referred to by a common name. Arrays can be used to save any type of data.
The general form of array declaration is:
type name[ ];
Some Examples are:
int A[ ]; //single dimensional array float ab[ ][ ]; //two dimensional array
Assigning is done as follows
A[ ] = new int[9];
ab[ ][ ] = {{1,2,3,4},{5,6,7}}
;
We can also initiate elements of the array using a loop. For instance if we assign elements to array A[ ] , then the index can be used to refer to a particular element in the array
|
index |
0 |
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
|
A= |
76 |
98 |
79 |
78 |
77 |
84 |
85 |
86 |
87 |
|
|
A[0] |
A[1] |
A[2] |
A[3] |
A[4] |
A[5] |
A[6] |
A[7] |
A[8] |
//findAverage.java //click here for code public class findAverage { public static void main (String[]args) { int a[] = { 76, 98, 79, 78, 77, 84, 85, 86, 89,90 }; float result = 0, avg=0; //initialise for (int i = 0; i < =9; i++) { result = result + a[i]; avg = result / 10; } System.out.println ("avg is " + avg); } } /* Output: avg is 84.2 */
Program 4.2: Find the maximum mark in a given array of marks data
//findMaximum.java //click here for code public class findMaximum { public static void main (String[]args) { int j, max = 0; int mark[] = { 88, 84, 72, 54, 67, 97, 54, 25 }; for (j = 0; j < mark.length; j++) { if (max < mark[j]) max = mark[j]; } System.out.println ("maximum: " + max); } } //Output maximum: 97
4.3 Array of objects
In array itself is an object. Just like this, we can have an array of objects. That is we assign objects of objects.
Example:
Student[] stud=new Student[3];
For creating them,
Student stud[0]=new Student; Student stud[1]=new Student; Student stud[2]=new Student;
Or, we can initialize using a for loop
for(int i=0;i<3;i++) Student stud[i]=new Student;
stud.length gives the number of elements in the array stud[ ].
Program 4.3 Program to sort an array of randomly obtained using the Math.random() method.
//sortArray.java Generate a set of 10 random numbers and sort them. //Click here for code import java.io.*; import java.util.*; public class sortArray { public static void main (String args[]) { //create an array int[] a = new int[10]; int i; for (i = 0; i < a.length; i++) a[i] = (int) (Math.random () * 100); //generate random numbers sort (a); for (i = 0; i < a.length; i++) System.out.println (a[i]); } public static void sort (int[]a) { //sort the array int n = a.length; int i, j, k; boolean flag; flag = false; for (i = 0; i < n; i++) { for (j = 0; j < n - 1; j++) { if (a[j] > a[j + 1]) { k = a[j]; a[j] = a[j + 1]; a[j + 1] = k; flag = true; } } if (!flag) break; } } } /* Output: 1 27 33 41 45 54 62 75 87 95 */
4.4 Java’s arrays are different from other language arrays
All programming languages support arrays. A Java array is guaranteed to be initialized and cannot be accessed outside of its range. The range checking comes at the price of having a small amount of memory overhead on each array as well as verifying the index at runtime, but the assumption is that the safety and increased productivity is worth the expense.
When we create an array of objects, we actually create an array of handles. All these handles are automatically initialized to null. When Java sees null, it recognizes that the handle in question is not pointing to the object. So, we should assign it a handle before using it, otherwise runtime error will occur. This is how array errors are prevented in Java.
Program 4.4 Program to perform addition and subscription on two matrices
//matrix.java //click here for code import java.io.*; public class matrix { int a[][] = new int[10][10]; int m,n; public matrix() { m=0;n=0; } public void getmat() { try { DataInputStream in; in =new DataInputStream(System.in); System.out.println("enter the order of the matrix"); String s=in.readLine(); m=Integer.parseInt(s); s=in.readLine(); n=Integer.parseInt(s); System.out.println("enter the elements of the matrix"); for(int i=0;i<m;i++) for(int j=0;j<n;j++) { s=in.readLine(); a[i][j]=Integer.parseInt(s); } } catch(Exception e) { System.out.println("I/O error"+e); System.exit(1); } } public matrix add(matrix ob) { matrix c = new matrix(); c.m=m;c.n=n; for(int i=0;i<m;i++) for(int j=0;j<n;j++) c.a[i][j]=a[i][j]+ob.a[i][j]; return c; } public matrix sub(matrix ob) { matrix c = new matrix(); c.m=m;c.n=n; for(int i=0;i<m;i++) for(int j=0;j<n;j++) c.a[i][j]=a[i][j]-ob.a[i][j]; return c; } public void showmat() { for(int i=0;i<m;i++) { for(int j=0;j<n;j++) System.out.println(a[i][j]+""); System.out.println(""); } } public static void main(String args[]) { matrix a = new matrix(); matrix b = new matrix(); matrix c = new matrix(); matrix d = new matrix(); a.getmat(); b.getmat(); c=a.add(b); d=a.sub(b); c.showmat(); d.showmat(); } } /*Output: enter the order of the matrix 2 2 enter the elements of the matrix 3 3 3 3 enter the order of the matrix 2 2 enter the elements of the matrix 1 1 1 1 4 4 4 4 2 2 2 2 */
4.5 Summary
In this chapter you have been introduced with arrays and strings. In arrays, you studied about single dimension and multi-dimension arrays. In strings you studied simple strings and string buffers.