Introduction To Array
Introduction To Array
Java array
• an object which contains elements of a similar data type. Additionally,
The elements of an array are stored in a contiguous memory location.
It is a data structure where we store similar elements. We can store
only a fixed set of elements in a Java array.
• Array in Java is index-based, the first element of the array is stored at
the 0th index, 2nd element is stored on 1st index and so on.
• Unlike C/C++, we can get the length of the array using the length
member. In C/C++, we need to use the sizeof operator.
• Java provides the feature of anonymous arrays which is not available
in C/C++.
• arrayRefVar=new datatype[size];
Example of Java Array
//Java Program to illustrate how to declare, instantiate, initialize
//and traverse the Java array.
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;
//traversing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}}
Declaration, Instantiation and Initialization of Java Array
for(data_type variable:array){
//body of the loop
}
Example:
//Java Program to print the array elements using for-each loop
class Testarray1{
public static void main(String args[]){
int arr[]={33,3,4,5};
//printing array using for-each loop
Output:
for(int i:arr)
33
System.out.println(i); 3
4
}} 5
Example: Compute Sum and Average of Array Elements
class Main {
average = ((double)sum / (double)arrayLength);
public static void main(String[] args) {
int[] numbers = {2, -9, 0, 5, 12, -25, 22, 9, 8, 12}; System.out.println("Sum = " + sum);
int sum = 0; System.out.println("Average = " + average);
}
double average;
}
// access all elements using for each loop
// add each element in sum
for (int number: numbers) {
sum += number; Output:
}
Sum = 36
// get the total number of elements
Average = 3.6
int arrayLength = numbers.length;
// calculate the average
// convert the average from int to double
In the example, we have created an array of named numbers. We have used the for...each
loop to access each element of the array.
Inside the loop, we are calculating the sum of each element. Notice the line,
marks[i]=input.nextInt();
totalMarks=totalMarks+marks[i];
}
}
}