java array

Array

An array is collection of homogenous data elements of a specific data type (i.e. int or float or char) that have been given a single name, which is stored at contiguous memory locations.
An array is a collection of similar data types (int a[10]) storing integer value.
array is a container object that hold values of homogenous type or holds a fixed number of values of a single type.
The length of an array is established when the array is created. After creation, its length is fixed.
Demonstration of array program

class arrayExample {
public static void main(String[] args) {
// declares an array of integers
int[] arr;
// allocates memory for 5 integers
arr = new int[5];
// initialize first element
arr[0] = 10;
// initialize second element
arr[1] = 20;
// and so third
arr[2] = 30;
// and so forth
arr[3] = 40;
// and so fifth
arr[4] = 50;

//output of array
System.out.println(“Element at index 0: “+ arr[0]);
System.out.println(“Element at index 1: “+ arr[1]);
System.out.println(“Element at index 2: “+ arr[2]);
System.out.println(“Element at index 3: “+ arr[3]);
System.out.println(“Element at index 4: “+ arr[4]);
}
}
Output :
Element at index 0: 10
Element at index 1: 20
Element at index 2: 30
Element at index 3: 40
Element at index 4: 50

Array program to Finding the largest element
public class arrayTest {
public static void main(String[] args) {
double[] arrayList = {1.9, 2.9, 3.4, 3.5};
// Print all the array elements
for (int i = 0; i < arrayList.length; i++) { System.out.println(arrayList[i] + " "); } double total = 0; for (int i = 0; i < arrayList.length; i++) { total += arrayList[i]; } System.out.println("Total is " + total); // Finding the largest element double max = arrayList[0]; for (int i = 1; i < arrayList.length; i++) { if (arrayList[i] > max)
{
max = arrayList[i];
}
System.out.println(“Max is ” + max);
}
}

output:
1.9
2.9
3.4
3.5
Total is 11.7
Max is 3.5

Array program with foreach Loops

public class arrayTest {
public static void main(String[] args) {
double[] arrayList = {1.9, 2.9, 3.4, 3.5};
// Print all the array elements
for (double element: arrayList)
{
System.out.println(element);
}
}
}

output:
1.9
2.9
3.4
3.5

BACK

NEXT