Sunday, June 13, 2010

Array for ICSE Java Programs

Array means collection of similar data’s in same named spaced location. Variables have some limitations, one of them is that it can hold only one value at a time. If we want to store number of values and we have to retain the values up to the end of the program then it would be very trouble some to work with normal variables. An array is also known as subscripted variable. Before using an array its type and name must be declared. Each element of an array can be referred by the array name and a subscript or index.

The general form of array declaration is:
type arrayname [ ];

In Java array is dynamic and is an object.
While creating an array, the following syntax is used
arrayname=new int[n];
while n is an integer variable which holds the size of the array. The values of n may be a constant value or user can set the value of n. That’s why array in java is dynamic.

Array can be initialized while declared using the following syntax
int arr [ ]= {2,3,4,5,6};
Here Compiler sets the size of the array and the values starting from 0 index. The maximum index of an array is always 1 less than the size of the array.
Since array is an object, it has a variable named length which holds the number of elements stored in an array and the value can be accessed using the following syntax
arr.length;

Advantages of Array
1. Array can hold number of values of same type in same location
2. Index or subscripts are generated automatically in array which helps us to access any value of an array directly.

Limitations of Array
1. Array can hold number of values but all are of same type.
2. Insertion of any element in a specific location of an array can be performed but it is very critical. The same for deletion

In our first example we will take age of five persons as input, store them in an array and will display.
import java.io.*;
class Arr
{
int a[ ];
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
void take(int n) throws IOException
{
a=new int[n];
for(int i = 0; i< n; i++ )
{
System.out.println(“Enter an Age=”);
a [i]= Integer.parseInt( br.readLine());
}
void display ()
{
System.out.println(“\nValues are as follows “);
for ( int i=0; i< n ; i++)
{
System.out.print ( “ “ + a [ i ] );
}
}
}

Related Post: BlueJ Programs on Numeric Array

No comments:

Post a Comment

Subscribe via email

Enter your email address:

Delivered by FeedBurner