Arrays in JAVA
An array is a collection of identical data object which are stored in consecutive memory location under common name. In other words, arrays are sets of values of the same type, which have the single name followed by an index.
Single Dimensional Array
Array declaration
In the array declaration, one must define the type of the array, name of the array, number of subscripts in the array and total number of memory locations to be allocated.
Syntax:
Data_type array_name[size]
Note : The size of the array must be an integer constant.
Example:
int empno[24];
float salary[24];
Initializing an array
The variables are initialized when they are declared, in the same way the arrays can also be initialized.
Syntax:
Data_type array_name[size] = { element1, element2, …..};
Example:
Int empno[6]={30,35,40,45,50,55 };
Float salary[6] = { 1000.50, 2500.25, 5500.45,35000.35, 4000.50, 5550.60 };
Assessing array elements
The array elements are accessed using the position of the element in the array. The position of the array start with 0 and ends with ( number_of_elements-1).
For example consider the following declaration
int empno[6];
30 35 40 45 50 55
empno[0] empno[1] empno [2] empno[3] empno[4] empno[5]
float salary[6];
1000.50 2500.25 5500.45 35000.35 4000.50 5550.60
salary[0] salary[1] salary[2] salary[3] salary[4] salary[5]
User can access these elements in any order he likes and use them in the same way as simple variable.
Example 1
import java.io.*;
public static void main(String args[])
{
int empno[6];
int i;
for(i=0;i<6;i++)>
{
System.out.println(empno[i]);
} for(i=0;i<6;i++)
{ System.out.println(“Employee No: “ + i+1 + empno[i]);
}
Output will be
Employee No: 30
Employee No: 35
Employee No: 40
Employee No: 45
Employee No: 50
Employee No: 55
Example 2
import java.io.*;
public static void main(String args[])
{
float salary[6];
int i;
for(i=0;i<6;i++)
{
System.out.println(salary[i]);
}
for(i=0;i<6;i++)
{
System.out.println(“Salary : “ + salary[i] );
}
Output will be
Salary : 1000.50
Salary : 2500.25
Salary : 5500.45
Salary : 35000.35
Salary : 4000.50
Salary : 5550.60
No comments:
Post a Comment