Thursday, 9 January 2014

Arrays

Array:

  • Array is a collection of similar type of elements that have contiguous memory location.
  • In java, array is an object the contains elements of similar data type. 
  • It is a data structure where we store similar elements. 
  • We can store only fixed elements in an array.
  • Array is index based, first element of the array is stored at 0 index.
Example: 
class Array{  
public static void main(String args[]){  
  
int a[]=new int[5];//declaration and instantiation  
a[0]=10;//initialization  
a[1]=20;  
a[2]=70;  
a[3]=40;  
a[4]=50;  
  
//printing array  
for(int i=0;i<a.length;i++)//length is the property of array  
System.out.println(a[i]);  
  
}}  

Output: 10
       20
       70
       40
       50


Advantage of Array

  • Code Optimization: It makes the code optimized, we can retrieve or sort the data easily.
  • Random access: We can get any data located at any index position.
  • Insertion, deletion and updation is easy.

Disadvantage of Array

Size Limit: We can store only fixed size of elements in the array. It doesn't grow its size at runtime. To solve this problem, collection framework is used in java.

Types of Array

  • Single Dimensional Array
                 Example:  int a[]={33,3,4,5};//declaration, instantiation and initialization  
  • Multidimensional Array
               Example:  int[][] arr=new int[3][3];//3 row and 3 column 

No comments:

Post a Comment