Array in Java


The simple data types we have considered so far represent single values. In many situations, however, it is necessary to process a collection of values that are related in some way, for example, a list of student marks or a collection of measurements resulting from some experiment. Processing such collections using only simple variables can be extremely cumbersome and for this reason, most high level languages include data structure known as array.

In java programming language a java array is considered as an object that has elements of similar data type. Java array is also considered as a data structure. A fixed number of elements can be stored in an array. The arrays are indexed based in java programming language and the first element of the array is stored at the index 0.


Advantage of java array:

In java there are two main advantages of array:

  1. The data can be sorted easily and the code is made optimized.
  2. Data can be fetched from anywhere that is any location or index from the array.


Disadvantage of Java array:

The main disadvantage of java array is that it has a fixed size. We can store a fix number of elements. The size of an array cannot be increased at run time.


Types of array in Java:

In Java programming language, there are two types of array:

  1. Single dimensional array
  2. Multi dimensional array


Single dimensional array in Java:

In some cases, it is better to store the data items in a sequence of main memory locations, each of which can be accessed directly. Such a data structure is called an array. In Java programming language, we can refer to each individual item or element in the array by a subscript in brackets.

For example, if the marks of ten students are to be processed in a program, we might use an array to store them. The computer must first be instructed to reserve a sequence of ten memory locations for the marks. The array for storing marks can be defined as

int marks[10];

here int specifies the type of elements or items that will be stored in the array and the word marks is the name of the array. The [10] following the array name tells how many variables of type int will be in our array and brackets tell the compiler that we are dealing with an array.

To refer to an individual element of the array, we use subscripts, the numbers in the brackets following the array name. This number specifies the element’s position in the array. In Java, all the array elements are numbered, starting at 0.

For example, the assignment statement

marks[4]=83;

stores the value 83 in the fifth location of the array because the numbering starts with 0. Thus, the last array element will have subscript one less than the size of the array. That means the array subscript will be in the range of 0 to 9.


Syntax to declare single dimensional array in Java:

An array in java can be declared using three different ways:

  1. dataType[] arr;
  2. dataType []arr;
  3. dataType arr[];


Instantiation of an array in Java:

Consider the following syntax to create an instance of an array in java:

arrayReferenceVariable = new datatype [size of array];


Example of single dimensional array:

Consider the following example in which we have declared an array and instantiated it then initialized it and then we will be traversing through the array:

CODE:

class ExampleArray {

public static void main (String args []) {

int arr [] = new int [5];

arr [0] = 2;

arr [1] = 4;

arr [2] = 6;

arr [3] = 8;

arr [4] = 10;

for (int j = 0; j < arr. length; j++) {

system. out. println (arr [j]); }

}

}

OUTPUT:

2

4

6

8

10

In the above example the statement int arr [] = new int [5]; is depicting the declaration and instantiation of the array. The statements like arr [0] = 2; are used to initialize the array. Then we printed the elements of the array by traversing through the array and by using the “for” loop. In the above example “length” is considered as a property of the array which determines the size or length of the array.


Declaration, Instantiation and initialization of array:

An array can be declared, instantiated and initialized together by using the following syntax:

int arr [] = {2, 4, 5, 7};

Now consider the following example in which we have printed the above array:

CODE:

class ExampleArray {

public static void main (String args []) {

int arr [] = {2, 4, 5, 7};

for (int j = 0; j < arr. length; j++) {

system. out. println (arr [j]);}

}

}

OUTPUT:

2

4

5

7

In the above example an array is declared, initialized and instantiated together at the statement int arr [] = {2, 4, 5, 7}. Then we used the “for loop” to traverse through this array. The counter variable of the loop that is “j” is used to traverse through the array. And then the array is printed by using the print statement and j, the counter variable as the subscript of the array.


Passing array to method in Java:

The java array can be passed to method. Consider the following example:

CODE:

class ExampleArray {

static void minimum (int a []) {

int minimum = a [0];

for (int j = 1; j < a. length; j++)

if (minimum > a [j]) {

minimum = a [j];

}

system. out. println (minimum);

}

public static void main (String args []) {

int arr [] = {2, 3, 4, 5};

minimum (arr);

}

}

OUTPUT:

2

The above code is finding the minimum value in the array by passing the array to the method. The statement minimum (arr); is used for this purpose.


Multidimensional array in Java:

There are many problems in which the data being processed can be naturally organized as a table or in the matrix form that is in the form of rows and columns. For example, if for each of twenty five different students, four test marks are to be processed in a program, the data can be arranged in a table having twenty five rows and four columns.

Student                            Test Number

Number                     

1 2 3 4
1 79 80 64 91
2 99 90 92 97
. . . . .
. . . . .
25 100 62 73 88

In this table, the four marks of student 1 are in the first row, the four marks of student 2 are in the second row, and so on. These one hundred data items can be conveniently stored in a two dimensional array. The declaration

Int marks[25][4];

This statement reserves one hundred memory locations for these data items. The array element

Marks[1][2]

Refers to the entry in the second row and third column of the table, that is, to the marks 92 earned by 2 students in test 3. In general,

Marks[i][j]

Refers to the entry in the row i and column j, that is, to the marks of student i in test j.


Syntax to declare multidimensional array in Java:

There are four different ways to declare multidimensional arrays in java programming language:

  1. dataType[][] arrayReferenceVariable;
  2. dataType [][]arrayReferenceVariable;
  3. dataType arrayReferenceVariable[][];
  4. dataType []arrayReferenceVariable[];


Example to instantiate Multidimensional Array in java:

Consider the following statement in which the multidimensional array is instantiated:

int[][] a = new int [2][2];

Here int [2][2] refers to 2nd row and 2nd column.


Example to initialize Multidimensional Array in java:

Consider the following statements in which the multidimensional arrays are initialized:

a [0][0] = 1;

a [0][1] = 2;

a [0][2] = 3;

a [1][0] = 4;

a [1][1] = 5;

a [1][2] = 6;

a [2][0] = 7;

a [2][1] = 8;

a [2][2] = 9;


Example of multidimensional array in Java:

Consider the following example in which we have declared and then instantiated and then initialized the 2D array and then printed it:

CODE:

class ExampleArray {

public static void main (String args []) {

int a [][] = {{1, 2, 3}, {4, 5, 6},{7, 8, 9}}

for (int i = 0; i < 3; i++) {

for (int j = 0; j < 3; j++) {

system. out. println ( a[i][j] + “”);

}

system. out. println ();

}

}}

OUTPUT:

1 2 3

4 5 6

7 8 9


What is the class name of java array?

Array in java programming language is considered as an object. When array is created a proxy class for it is also created and the name of this class can be obtained by using the getclass (). getname () method. Consider the following example:

CODE:

class ExampleArray {

public static void main (String args []) {

int a [] = {1, 2, 3};

class c = a. getClass ();

String name = c. getName ();

system. out. println (name);

}

}

OUTPUT:

I

In the above example an array “a” is declared as it is an object in java then the class of this object is determined by getClass () and getName () method. The name of the class is stored in a string type variable “name”. Then this variable is printed and we got the name of the variable in the output.


Copying a Java array:

In java programming language an array can be copied to another array by using the arraycopy method of the system class.


Syntax of arraycopy method:

The following is the syntax of the arraycopy method in java:

public static void arraycopy () {

Object src, int srcPos, object dest, int destPos, int length

}


Example of arraycopy method:

The following is the example of arraycopy method in java:

CODE:

class ExampleArrayCopy {

public static void main (String args []) {

char [] copyFrom = {‘a’, ‘d’, ‘s’, ‘e’, ‘f’, ‘t’, ‘h’, ‘y’, ‘f’, ‘g’}

char [] copyTo = new Char [7];

system. arraycopy (copyFrom, 2, copyTo, 0, 7);

system. out. println (new String (copyTo));

}

}

OUTPUT:

sefthyf

In the above example we have declared an array of char type named copyFrom of content of which we will be copying to the new array. Another array of char type is declared named copyTo in which we will be copying the content. The statement, “system. arraycopy (copyFrom, 2, copyTo, 0, 7)” of the above code decides that which elements of the array should be copied to the newly created array. Then the statement “system. out. println (new String (copyTo))” is used to print the newly created array in which we have the elements of the previous array.


Addition of two matrices in Java:

Consider the following example in which two matrices are added:

CODE:

class ExampleArray {

public static void main (String args []) {

int x [][] = {{1, 2, 3}, {4, 5, 6}};

int y [][] = {{1, 2, 3}, {4, 5, 6}};

int z [][] = new int [2][3];

for (int i = 0; i <2; i++) {

for (int j = 0; j <3; j++) {

z [i][j] = x [i][j] + y [i][j];

system. out. print (z[i][j]+ “”);

}

system. out. println ();

}

}}

OUTPUT:

2 4 6

8 10 12

In the above example two 2D arrays are declared and another array 2D to store the sum of the first two arrays. Then we used nested for loop to add and then to print the new array.