Monday, December 26, 2016

Implementation of Arrays in Java

Definition:
Array concept in java is same as other programming languages like C/C++, .net etc. but implementation here is different. An array is a homogenous collection of data. Array is having contiguous memory locations. Contiguous, not continuous there is a difference between these 2 words the Contiguous means adjacent and Continuous means continuous without stopping, no matter it is adjacent or not. So, array is contiguous.
As an example, take salary of 50 employees from user and print average. Without array it will take minimum 100 lines of code and will also degrade the performance of program, but using array it will only take 7 to 8 lines.
In traditional languages like C/C++ the arrays were static which means memory allocation for array was static and the size needs to be decided at compile time. It causes memory wastage because we need to decide the size before compilation. But in java arrays are dynamic, so no need to mention the size of array.

Syntax:

int x[];
int []x;

both of above syntax is allowed in java, the difference between them is, by second way we can declare multiple arrays with single brackets [] like this:
int []x,y,z;
iny x[], y[], z[];

Let’s take a simple example:

Create a file ArrayDemo.java in com.dev21century package:
package com.dev21century;

public class ArrayDemo {

      public static void main(String[] args) {

            int x[];
            x = new int[10];

            //adding elements in array
            for(int i = 0;i<x.length;i++)
            {
                  x[i] = i + 1;
            }
           
            //Retrieving elements from array
           
            for(int i = 0;i<x.length;i++)
            {
             System.out.println("x["+i+"] = " + x[i]);
            }
      }

}

Output:


In java everything is represented as an object except primitive data type, but that is also implicitly treated as an object, not explicitly.

Anonymous Array:
An anonymous array is an array with no name; it is used for temporary purpose. Let’s take this scenario:

ArrayDemo.java

package com.dev21century;
public class ArrayDemo {

      static int max(int x[])
      {
            return 30;
      }    
     
      public static void main(String[] args) {
           
            int z[] = {10,20,30};
            int result = max(z);
            System.out.println("Max no = " + result);
      }
}

In above program once z is passed in max() method then there is no use of z, it’s a memory wastage.
The solution of this issue is creating an anonymous array. Now, let’s alter above program as follows:

package com.dev21century;
public class ArrayDemo {

      static int max(int x[])
      {
            return 30;
      }    
     
      public static void main(String[] args) {
           
            int result = max(new int[]{10,20,30});
            System.out.println("Max no = " + result);
      }
}

Output:
Max no = 30

Double Dimension Array:
The two Dimension array is a matrix representation of array, where data stored in rows and column format. There is no two dimension array concept in any programming language, only array of array concept do exist. There is no row / column or matrix representation in memory, all memory allocated contagiously, a single array of many arrays.

Let’s take a scenario where 2D array is required:
Take marks of 5 subjects of 100 students and calculate percentage. When we refer a single dimension array for above problem, we need to take multiple arrays then those arrays will be allocated at different locations. Finally performance of the program will be impacted.

Syntax:
            int x[][] = new int[105][5];
            int []y[] = new int[105][5];
            int [][]z = new int[105][5];
            int []a[] = new int[105][];

We can declare 2D array in above ways. We must at least provide the size if x dimension (number of rows). In java we can specify any number of columns for different rows. Like this:
            x[0] = new int[10];
            x[1] = new int[5];
            x[2] = new int[20];

Initialization of 2D array:
We can initialize the 2D array in following ways:

            int array[][] = {
                        {10,20,30},
                        {30,40},
                        {50,60,60,90}
                        };
            int array2[][] = {
                        {1,2,3},
                        {4,5,6,},
                        {7,8,9}
                        };
Syntax of anonymous 2D array:

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

Array of reference variables:
Let’s take this example, create a file ArrayDemoRef.java in com.dev21century package

package com.dev21century;
public class ArrayDemoRef {
   int x ;
   public static void main(String args[])
   {
     ArrayDemoRef array[] = new ArrayDemoRef[5];//Line No 7
     for(int i = 0;i<array.length;i++)
     {
      array[i] = new ArrayDemoRef();//Line No 10
      array[i].x = i+5;
     }
     
     for(int i = 0;i<array.length;i++)
     {
      System.out.println("array["+i+"].x = " + array[i].x);
     }
   }
}

Output:


In above program at line number 7 we are creating an array of reference variables of ArrayDemoRef type. Please be clear, this is not an array of object, we are allocating objects for each reference variable at line number 10. Below is the diagrammatical representation of program in memory:


As we know that static reference variables are always allocated at stack area of memory and dynamic objects are allocated at heap area of memory. Here, the reference array is allocated at stack area whereas objects are allocated at heap area.

Anonymous reference array:
Syntax –
new ArrayDemoRef[]{new ArrayDemoRef(), new ArrayDemoRef(),
                        new ArrayDemoRef()}

Example:
Modify above program as:

package com.dev21century;

public class ArrayDemoRef {
      int x ;
      ArrayDemoRef(int x)
      {
            this.x=x;
      }
      static void display(ArrayDemoRef array[])
      {
            for(int i = 0;i<array.length;i++)
            {
                  System.out.println("array["+i+"].x = " + array[i].x);
            }
      }
     
      public static void main(String args[])
      {
            display(new ArrayDemoRef[]{new ArrayDemoRef(10),new ArrayDemoRef(20),
                        new ArrayDemoRef(30)});
     
      }
}

Output:

No comments:

Post a Comment