Wednesday, 12 September 2012

Java program codes: Array Tutorial in Java

Array Tutorial in Java

In this section you will be introduced to the concept of Arrays in Java Programming language. You will learn how the Array class in java  helps the programmer to organize the same type of data into easily manageable format.
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 can not be altered when required.
The Array class implicitly extends java.lang.Object so an array is an instance of Object.
Advantages of Java Array:
  1. An array can hold primitive types data.
  2. An array has its size that is known as array length.
  3. An array knows only its type that it contains. Array type is checked at the compile-time.
Disadvantages of Java Array:
  1. An array has fixed size.
  2. An array holds only one type of data (including primitive types). 
  3. Now lets study the structure of Arrays in java. 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.
    Lets have a close look over the structure of Array. 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 as shown  in the figure. Each element is holding a distinct value. Here the first element is refrenced 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
    The figure below shows the structure of an Array more precisely.


    As we declare a variable in Java, An Array variable is declared the same way. 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];
    Here is an example that creates an array that has 5 elements.
    public class Array
    {
     public static void main(String[] args)
     {
      int[] a = new int[5];
     }
    }
  4. 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.
    Lets see a simple example of an array,
    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, as shown.
    Output for the given program:
    C:\tamana>javac Sum.java

    C:\tamana>java Sum
    5050

    C:\tamana>
    Download this example.
    We have already discussed that 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 a 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 upto 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.
    After learning all about arrays, there is still one interesting thing left to learn i.e. copying arrays. It means to copy data from one array to another. The precise way to copy data from one array to another is
    public static void arraycopy(Object source,
                       int srcIndex,
                       Object dest,
                       int destIndex,
                       int length)
    Thus apply system's arraycopy 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, 05);
      System.out.println(new String (copyTo));
      }
    }
    Output of the program:
    C:\tamana>javac ArrayCopyDemo.java
    C:\tamana>java ArrayCopyDemo
    cdefg
    C:\tamana>
    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 arraycopy method takes the copied 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", like this :
    Following image illustrates the procedure of copying array from one to another.

    Donwload this example.
    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. We already know about for loop. 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 i=0; i<a2.length; i++) {
         for (int j=0; j<a2[i].length; j++) {
             System.out.print(" " + a2[i][j]);
         }
         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.
    Here is the complete code of the example:
    public class twoDimension{
      public static void main(String[] args) {
      int[][] a2 = new int[10][5];
      for (int i=0; i<a2.length; i++) {
      for (int j=0; j<a2[i].length; j++) {
      a2[i][j= i;
      System.out.print(" " + a2[i][j]);
      }
      System.out.println("");
      }
      }
    }
    Here is the output for the program:
    C:\tamana>javac twoDimension.java
    C:\tamana>java twoDimension
     0 0 0 0 0
     1 1 1 1 1
     2 2 2 2 2
     3 3 3 3 3
     4 4 4 4 4
     5 5 5 5 5
     6 6 6 6 6
     7 7 7 7 7
     8 8 8 8 8
     9 9 9 9 9
    C:\tamana>_
    Download this program
    So far we have studied about the one-dimensional and two-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, supports 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 ued 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.

No comments:

Post a Comment