Array Concept Simplified in Java

The first implementation to store objects in any programing language is variable no doubt, like
int a=10;
int b=20;
so if we need to store 10 values, We will create 10 different variables.

What is the problem here?
  • Well more the number , we want to store , more the variables we need to use.  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 variable. 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. More advanced concept of the java language like loop can not 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 collection, of type indexed, for homogeneous data type elements.
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 main advantages are:
  • Arrays are fixed sized. So once the array got created, even if the programmer or the application needs to store more, Simply can not as of size limitation
  • As this is of fixed size , for better programming control, Programmer need to know the array size before hand. This is always not possible in 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 complexity of the program.
  • Array can hold only homogenous data.  
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 object array...Since Object is the father for all other object. 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.
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.