Array Concept Simplified in Java

The first implementation to store values in any programming language is variable, like
int a=10;
int b=20;
so if we need to store 10 values, We need to create 10 different variables.
Simple!!

What is the problem here?
  • If we want to store more data, we need to use more variables. Imagine a scenario where we are trying to capture different marks obtained by class -II students in different subjects. Assume this particular school has 4 different subjects for Class-II and it is having 30 students. So!!! we need to create 4*30=120 variables!!!
  • Think about readability!!! may be there will minimum 120 lines to declare, initialize and assign values to these variables. Readability will be worst for these cases.
  • No programmatic control over these variables. Let us say we want to fetch values one by one and display, for this case minimum we need to write again 120 lines of code. The more advanced concept of the Java language like loop cannot be applied on this.
So, What could be the solution?? we want to reduce the variable count, Java has come up with a concept called Array.
Array: An array is a very common data structure. It is the most efficient way to store and access objects(object handles).It is a collection of type-indexed, homogeneous data elements[All the elements must be the same datatype i.e an array holds multiple values of the same type(primitive type or object reference or instances of the same class type)].So number of data items are collected together into a single unit and provided a name is called an Array.in more generic words, Array is a sequence of items referred by a name, The items in an Array are numbered(index).Individual items are referred by the position number. Array is a linear sequence for storing objects.In an array, a sequence of objects\elements packaged together under one single identifier name.The speed is very fast while accessing an Array but the size is fixed. Once defined Array is of fixed size and can not be increased to accommodate more elements. It starts with index zero(0). An array is defined and used with a square bracket called indexing operator-[].We can find out the length of an Array but can not tell how many elements are there in the Array.

The definition of Array is a numbered Sequence of items which are all of the same type. The total number of items in an array is called length of the Array. The position number of an item in an Array is called the index of that item. The type of the individual items in an Array is called the base type of the Array.(Base type can be primitive type or class name or interface name) 
If base type of an Array is String,It is referred as an Array of String Similarly for int, it is referred as an Array of ints. The Array can be visualized as a container not values.It can hold a value of a specific type(base type) which can be changed. Values are stored in an Array.Each individual variables that make the Array is called the Elements of the Array.
Java supports C and C++ style array declaration like int myArray[]; and also support Java-style array declaration int[] myArray;
In this way ab object is also a data structure of named instance variable.Array can hold Primitive Data types and Objects(set of buttons,text boxes).

We can declare an array in the following manners:

  1. (Element type)[] (Array name)=new (element type)[size]
  2. (Element type) (Array name)[]=new (element type)[size]
  3. (Element type)[] (Array name)={element1,element2.....elementN}
Where (Element type) is the type or identifier of the array.size is the number of the element specified to be reserved for the array in the memory. This size attribute is similar to a public final variable of an array. Once it is specified or defined, we can not change it.The bracket [] operator is to recall the syntax for referring individual items in an Array.
Example -

int myArray[]=new int[7];
int myArray[] does not create an array, It is just a declaration. Once declared, the compiler has no idea about the size of the Array. At this point what we have, is the handle of the Array that refers to the Array. The reference variable will have no value as no space has been allocated to the Array. To create storage space for the array we must initialize it. Array gets created when we use the new operator along with the size of that Array.new returns a reference to the myArray variable.
Once we create an array with the new operator, all elements of the array are initialized with default values until actual values are placed in array position. Any elements of the Array can hold a value of null meaning it is not pointing to anything.Java Array variables can not hold the Array rather they can only point or refer to an Array.
As Arrays are created by using new operator, they are objects. Being an Object they belong to a class(Object the super class of all classes). The elements of the array are essentially instance variable of the Array Object.

In the above example:
If an Array is referred by myArray then element at index 0 is referred by myArray[0],index 1 is referred by myArray[1] and index-N in myArray is referred by myArray[N] .
  

There are three commonly used ways to populate an array:

  • Population on Declaration/Early Initialization
  • Using loop
  • Population when required/Dynamic Generation
Population on Declaration or Early Initialization:

In this way, no need to use the 'new' operator to create the array. The size of the array is determined by the elements present is the curly braces or bracket.
String[] myFruit={"Apple","Banana","Grape"}
This code will create an array named myFruit of length 3
Students[] stud={stud1,stud2,stud3....,studN}
This code will create an array of Student object named stud of length N.If one of the element is null, a null object reference is placed in the array.


Using Loop:
A loop is used to populate the items in an array. This is referred to as a semi-dynamic population.
Example: The below example declares an integer type array of size 5. As and when the array is created with new operator it is also pre-populated with default values. With the below example, we will assign real values to the Array- myValue

int[] myValue=new int(5);
for(int i=0;i<myValue.length;i++)
{
myValue[i]=i;
}


Populate When Required:
This is an advanced technique where the array position can be populated as when required. Here also the array is created with the new operator and some of the position is having actual values but rest are having the default values. They are used when there is a need for them.

Example: Assume that a car seller is having 5 space in his shop. Now in a given day, three of the space is occupied by three different cars. Rest two are empty. So he will update his database with an array of five cars and out of which he will fill the details of three cars. Rest two he will only fill when he will have two more cars.

Cars myCar=new Car[5];
myCar[0]= new Car();
myCar[1]=new Car();
myCar[2]=new Car();
We can create an array dynamically in the below way, but in this process, the array is created only at the beginning of the execution. So every time we run this program, method myRand(int a) will return a value that will be treated as a size of the array.

int a[]=new int[myRand(20)];
int myRand(int a)
{
return Math.abs(rand.nextInt(a));
}
Once the array is created in the runtime, elements of primitive datatypes are initialized to default values. And objects are initialized to null, in case of non-primitive data elements.
If we work with an array of class objects i.e non-primitives, we must need to use the new operator to create its array of handles.
Let us see one more example: Here we are creating an array whose size is an output of a function called myRand(). So every time the program runs, it just creates the array with dynamically generated size provided by the function. In the main() method, Integer a[]=new Integer[5] is an array of handles. They get initialized in the next new statement i.e a[i]=new Integer(20);

import java.util.Random;

public class ArrayTest {
 static Random rand=new Random();
 static int myRand(int num)
 {
  return Math.abs(rand.nextInt(num));
 }
 public static void main(String[] args) {
  
  Integer a[]=new Integer[myRand(10)];
  System.out.println("Array Size- "+a.length);
  for(int i=0;i<a.length;i++)
   {
   a[i]=new Integer(myRand(100));
   System.out.println("The element at "+i+" is "+a[i].intValue());
   }
 }
}

The output is very interesting:
1st Run:
Array Size- 2
The element at 0 is 96
The element at 1 is 41
2nd Run:
Array Size- 6
The element at 0 is 4
The element at 1 is 31
The element at 2 is 46
The element at 3 is 13
The element at 4 is 85
The element at 5 is 59

How Arrays Internally Work-My view:
Since (base type) like int[] is a class, we can use it to declare a variable like-
int[] rollNumber;
This rollNumber is capable of referring an Array on ints. Initially the rollNumber is null if it is a member variable in a Class or undefined if it is a local variable in a method.
The new operator is used to create a new Array Object which is then assigned back to rollNumber.
int[] rollNumber=new int[10];
This line creates an array of 10 integer rollNumbers. The Constructor of the base type (int here) is given a number(int) to inform the JVM that  the length of the Array will be equal to that number(10 here).The length of an Array is an instance variable in Array object. The length of the Array is a variable but a final instance variable.So once it is initialized we can not change it.

The newly created Arrays are Automatically filled with default values. For numbers it is zero. for boolean it is false,for Characters it is unicode number zero, for Objects it is null. It is guranteed to be initialized.

The bracket ([]) will contain either integer or an expression that can be evaluated as integer.
So
rollNumber[2] and rollNumber[2*someOtherValue] both are legal but they must fall in the range of 0 to Array length-1.
Now since every usage of variable in java talks about memory location so when we said rollNumber[N] it is actually does the follwing:

  1. Get the pointer that is stored in rollNumber variable or Array variable
  2. Find the Array object by following the pointer
  3. Obtain the value of N provided by the user.
  4. Allocate the N numbers of storage and return the pointer that is reference to the Array variable in this case rollNumber.  

The pictorial view is something below:
rollNumber------>10 rollNumber.length
                             ---->rollNumber[0]=>value 0   // these are elements of the Array rollNumber
                             ---->rollNumber[1]=>value 0
                             ---->rollNumber[2]=>value 0
                            ...................
                            ...................
                             ---->rollNumber[N]=>value 0

Array Size and boundaries are two different things. If ArraySize is 100, the boundaries will be from 0 to 99.We can create one dimensional, two dimensional and three dimensional array also. But as arrays can not grow in size. The are fixed sized N-dimensional arrays. They have to be created either using curly brackets or using new operator.
It is also possible to create and initialize an array in the following ways:


public class myArray{
public static void main(String args[])
{
//1-D Array:
Integer[] a=
{
new Integer(1),
new Integer(3),
new Integer(5),
};
Integer[] b=new Integer[]
{
new Integer(1),
new Integer(3),
new Integer(5),
};
// The commas for the last line is optional, Community says, it is best to give it for better readability
//2D Array:
int c[][]={
{1,2,3},
{4,5,6},
};
//3D Array:
int d[][][]=new int[2][3][4];
//we can use N dimensional dynamic Array with myRand()method also. MyRand() is defined earlier
int e[][][]=new int[myRand(10)][][];
for(int j=0;j<e.length;j++)
{
e[j]=new int[myRand(5)][];
 for(int k=0;k<e[j].length;k++)
 {
  e[j][k]=new int[myRand(3)];
 }
}

} 

Why do we need to create a definition for Array like int a1[], or int[] a2 when they do not represent an Array in the true sense?
Well, they are only required as the coder may use them to copy one Array to other.

int a1[]={1,2,3,4};
int a2[];
a2=a1;
Here is an example to showcase if we try to add different types into an array of different type then what happens:

Students stu[]=new Students[100]
// This statement will create 100 students variable of type student
stu[0]=new Student();
//this will create the first student
stu[1]=new Customer();
// Since this is not a homogenous object ,Compiler will throw an error "InCompatible types found: Customer required Student"

This problem can be resolved by using the object array...Since Object is the father for all other objects. The example could be...
Object[] obj=new Object[100]
// This statement will create 100 object variables of type Object
obj[0]=new Student();
//this will create the first student
obj[1]=new Customer();
//this will create the first Customer

But yes this is not a good practice.
Size of the Array:The size of an array falls between 0 and array.length-1. That means all the elements should be well inside this boundary. This boundary is called Array bounds. Programmer can access elements from this bounds. If the coder tries to access an element which is out side of this bound, the compiler will throw an error-ArrayIndexOutOfBoundException

The main advantages are:
  • It is indexed hence programmatic control is possible on Array
  • It can represent multiple values using a single variable
  • As a result, readability improves a lot. 
  • The speed of accessing the values are faster.
  • It is superior than other generic containers(Vectors,stack,HashTable etc)
  • We get a compile time checking of the type of the data it holds.
The main disadvantages are:
  • Arrays are fixed sized. So once the array got created, even if the programmer or the application needs to store more, Simply cannot as of size limitation
  • As this is of fixed size, for better programming control, Programmer needs to know the array size beforehand. This is always not possible in a real time scenario.
  • There is no underlying data structure, So ready-made data support is not possible.
  • For all array related requirements, programmers need to write code explicitly. This increases the complexity of the program.
  • The array can hold only homogeneous data.
If Class X is subclass of Class Y then Class X[] is automatically a subclass of Class Y[].
Array Concept Simplified in Java Array Concept Simplified in Java Reviewed by Animesh Chatterjee on July 14, 2013 Rating: 5

No comments:

Powered by Blogger.