What is a variable?
Variables are called placeholders.
so when you say
int x = 10;
It means x is a placeholder for value 10.
If you want to declare 1000 variables then you have to declare them all one by one. This will not only make your program long but also it will affect code readability.
So what is its solution?
Array
With Array, we can represent multiple values with a single variable.
An array is an indexed collection of a fixed number of homogeneous data elements.
And this index starts at 0 and goes to n-1. where n is the number of elements.
How to declare Array
- datatype[] variable_name = {put elements seprated by commas};
- datatype variable_name[] = {put elements seprated by commas};
- datatype[] variable_name = new datatype[initial size];
Example:
int[] myAraay = {4,5,6,7};
int myarray[] = {4,5,6,7};
int[] myarray2= new int[10];
Conclusions:
- similar kind of data (homogenous elements)
- boundary condition. You can not increase or decrease the size.
- indexing start from zero
- continuous ,memory allocation
The main advantage of Array is we can represent multiple values with a single variable. so the readability of code will be improved.
Limitation of Array
- Arrays are fixed in size. i.e. once we create an array with some size. there is no chance of increasing or decreasing it. Its size is based on our requirement. Hence to use arrays, compulsory we should know the sie in advance which may not be possible always.
- Arrays concept is not implemented on some standard data structure hence ready-made method support is not available. for every requirement, we have to write the ode explicitly which is the complexity of programming.
- we have Arrays class which has ready-made methods available.
- Arrays hold only homogeneous data members.
student[] s = new student[1000];
s[0] = new student();
//rights[1] = new customer();
//wrongwe can solve this problem by using object arrays
Object[] o = new Object[1000];
o[0] = new student();
//valid0[1]= new customer();
//valid
Comments
Post a Comment