Tuesday, November 10, 2015

Array in JAVA with Example

In this post we will discuss and learn about Arrays in Java with example. This is one of the core concept in the Java Programming language. As a java developer must have strong knowledge on arrays in java.

Array is the  most important thingin any programming language.An array is a data structure that represents an index collection of fixed no of homogeneous data elements.Array isone of the fundamental data structure and most of other data structures are based upon it e.g. List, Hash tables are based upon arrays.It also store the values in memory at the fixed size.

Declaration of Array :

 int num[]; 
     (or)
 int num = new int[2];

Sometime user can declare an array and it's size simultaneously. such as follows
                                
int num[] = {50,20,45,82,25,63};  


Internal representation of an array:




 Advantage of an 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

Disadvantages of an Array:

Set 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.

Example :

class Testarray{  
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:
Javac Testarray.java //for compilation

java Testarray   //to run the program

10
20
70
40
50

        
                          


No comments:

Post a Comment

High Paying Jobs after Learning Python

Everyone knows Python is one of the most demand Programming Language. It is a computer programming language to build web applications and sc...