Java Arrays

Java Arrays


Program data is stored in the variables and takes the memory spaces, randomly. However, when we need the data of the same type to store in the contiguous memory allocations we use the data structures like arrays. To meet this feature java has provided an Array class which abstracts the array data-structure.
The java array enables the user to store the values of the same type in contiguous memory allocations. Arrays are always a fixed length abstracted data structure which cannot be altered when required.
The Array class implicitly extends java.lang.Object so an array is an instance of Object.

Structure of a Java array:
Array is the most widely used data structure in java. It can contain multiple values of the same type. Moreover, arrays are always of fixed length i.e. the length of an array cannot be increased or decreased.
Array contains the values which are implicitly referenced through the index values. So to access the stored values in an array we use indexes. Suppose an array contains “n” integers. The first element of this array will be indexed with the “0” value and the last integer will be referenced by “n-1” indexed value.
Presume an array that contains 12 elements. Each element is holding a distinct value. Here the first element is referenced by a [0] i.e. the first index value. We have filled the 12 distinct values in the array each referenced as:
a [0]=1
a [1]=2

a [n-1]=n
a [11]=12

Declaring a Java array:
Array variable has a type and a valid Java identifier i.e. the array’s type and the array’s name. By type we mean the type of elements contained in an array. To represent the variable as an Array, we use [] notation. These two brackets are used to hold the array of a variable.
By array’s name, we mean that we can give any name to the array; however it should follow the predefined conventions. Below are the examples which show how to declare an array:
int [] array_name;   //declares an array of integers
String [] names;
int [][] matrix;  //this is an array of arrays
It is essential to assign memory to an array when we declare it. Memory is assigned to set the size of the declared array. For example:
int [] array_name = new int [5];
Example: An example that creates an array that has 5 elements.
public class Array
public static void main (String [] args)
int [] a = new int[5];

Initialization of Java array:
After declaring an array variable, memory is allocated to it. The “new” operator is used for the allocation of memory to the array object. The correct way to use the “new” operator is
String names [];
names = new String [10];
Here, the new operator is followed by the type of variable and the number of elements to be allocated. In this example [] operator has been used to place the number of elements to be allocated.
public class Sum
public static void main (String [] args)
int [] x = new int [101];
for (int i = 0; i<x.length; i++)
x [i] = i;
int sum = 0;
for (int i = 0; i<x.length; i++)
sum += x[i];
System.out.println (sum);
In this example, a variable ‘x’ is declared which has a type array of int, that is, int []. The variable x is initialized to reference a newly created array object. The expression ‘int [] = new int [50]’ specifies that the array should have 50 components. To know the length of the Array, we use field length.

Usage of arrays:
To refer an element within an array, we use the [] operator. The [] operator takes an “int” operand and returns the element at that index. We also know that the array indices start with zero, so the first element will be held by the 0 index. For Example:
int month = months [4];//get the 5th month (May)
Most of the times it is not known in the program that which elements are of interest in an array. To find the elements of interest in the program, it is required that the program must run a loop through the array. For this purpose “for” loop is used to examine each element in an array. For example:
String months [] =
{“Jan”, “Feb”, “Mar”, “Apr”, “May”, “Jun”,
“July”, “Aug”, “Sep”, “Oct”, “Nov”, “Dec”};
//use the length attribute to get the number
//of elements in an array
for (int i = 0; i < months. Length; i++) {
System.out.println (“month: ” + month[i]);
Here, we have taken an array of months which is,
String months [] =
{“Jan”, “Feb”, “Mar”, “Apr”, “May”, “Jun”,
“July”, “Aug”, “Sep”, “Oct”, “Nov”, “Dec”};
Now, we run for loop to print each element individually starting from the month “Jan”.
for (int i = 0; i < months. Length; i++)
In this loop int i = 0; indicates that the loop starts from the 0th position of an array and goes up to the last position which is length-1,  i < months. Length; indicates the length of the array and i++ is used for the increment in the value of i which is i = i+1.

Copying Arrays:
Copying arrays means to copy data from one array to another. The precise way to copy data from one array to another is
public static void array copy (Object source,
int srcIndex,
Object dest,
int destIndex,
int length)
Thus apply system’s array copy method for copying arrays. The parameters being used are,
•    src: the source array
•    srcIndex: start position (first cell to copy) in the source array
•    dest: the destination array
•    destIndex: start position in the destination array
•    length: the number of array elements to be copied.
The following program, ArrayCopyDemo (in a .java source file), uses arraycopy to copy some elements from the copyFrom array to the copyTo array.
public class ArrayCopyDemo{
public static void main(String [] args){
char[] copyFrom = {‘a’,’b’,’c’,’d’,’e’,’f’,’g’,’h’,’i’,’j’};
char [] copyTo = new char[5];
System.arraycopy (copyFrom, 2, copyTo, 0, 5);
System.out.println (new String (copyTo));
In this example the array method call begins the copy of elements from element number 2. Thus the copy begins at the array element ‘c’. Now, the array copy method takes the copy element and puts it into the destination array. The destination array begins at the first element (element 0) which is the destination array copyTo. The copyTo copies 5 elements: ‘c’,’d’, ‘e’, ‘f’, ‘g’. This method will take “cdefg” out of “abcdefghij”.

Two-dimensional arrays:
Two-dimensional arrays are defined as “an array of arrays”. Since an array type is a first-class Java type, we can have an array of ints, an array of Strings, or an array of Objects. For example, an array of ints will have the type int []. Similarly we can have int [] [], which represents an “array of arrays of ints”. Such an array is said to be a two-dimensional array.
The command int [] [] A = new int [3] [4] declares a variable, A, of type int [] [], and it initializes that variable to refer to a newly created object. That object is an array of arrays of ints. Here, the notation int [3] [4] indicates that there are 3 arrays of ints in the array A, and that there are 4 ints in each of those arrays.
To process a two-dimensional array, we use nested for loops. A loop in a loop is called a Nested loop. That means we can run another loop in a loop. Notice in the following example how the rows are handled as separate objects.
Code: Java
int [][] a2 = new int[10][5];
// print array in rectangular form
for (int r=0; r<a2.length; r++) {
for (int c=0; c<a2[r].length; c++) {
System.out.println (” ” + a2[r] );
System.out.println (“”);
In this example, “int [] [] a2 = new int [10] [5];” notation shows a two-dimensional array. It declares a variable a2 of type int [] [], and it initializes that variable to refer to a newly created object. The notation int [10] [5] indicates that there are 10 arrays of ints in the array a2, and that there are 5 ints in each of those arrays.

Multi-dimensional arrays:
To store data in more dimensions a multi-dimensional array is used. A multi-dimensional array of dimension n is a collection of items. These items are accessed via n subscript expressions. For example, in a language that supports it, the element of the two-dimensional array x is denoted by x [i, j].
The Java programming language does not really support multi-dimensional arrays. It does, however, support an array of arrays. In Java, a two-dimensional array ‘ x’ is an array of one-dimensional array. For instance,
int [][] x = new int[3][5];
The expression x[i] is used to select the one-dimensional array; the expression x[i] [j] is used to select the element from that array. The first element of this array will be indexed with the “0” value and the last integer will be referenced by “length-1” indexed value. There is no array assignment operator.
Advantages of Java Array:
•    An array can hold primitive types data.
•    An array has its size that is known as array length.
•    An array knows only its type that it contains. Array type is checked at the compile-time.

Disadvantages of Java Array:
•    An array has fixed size.
•    An array holds only one type of data including primitive types.



This site uses Akismet to reduce spam. Learn how your comment data is processed.