Array :
Array is an basic data structure used to store a collection of elements sequentially.
Elements in an array can be accessed randomly because elements in array can be identified by array index.
We have one dimensional array and multi-dimensional array.
One dimensional array is known as Linear array.
Example :
// Example :
Array is an basic data structure used to store a collection of elements sequentially.
Elements in an array can be accessed randomly because elements in array can be identified by array index.
We have one dimensional array and multi-dimensional array.
One dimensional array is known as Linear array.
Example :
Here , we can access 2 as num[0] , 6 as num[3]
Operations in Array :
Initialize
Length of an array
Access an Element
Iterate all the Elements
Modify Elements
Sort
// Example :
package com.techyield.operationsinarray;
import java.util.Arrays;
public class OperationsinOneDimensionalArray {
public static void main(String[] args) {
//Intialize
int [] array1 = new int[5];
int [] array = {1,2,3,4,5,6};
// Getting Length
System.out.println("The Size of array1 is "+array1.length);
System.out.println("The Size of array2 is "+array.length);
// Access 4th element in array2
System.out.println("The 4th element in array"+array[3]);
// Iterate all the elements in array
// First Version
System.out.println("Fetching elements using for loop");
for(int i =0; i < array.length; i++) {
System.out.println(" "+array[i]);
}
System.out.println();
System.out.println("Fetching elements from array using forEach ");
for(int k : array) {
System.out.println(" "+k);
}
System.out.println();
// Modify Elements
System.out.println("Modify 3rd ELement in array ");
array[2]= 9;
for(int p : array) {
System.out.println(" "+p);
}
System.out.println(" Sort the Elements");
// Sort the Elements
Arrays.sort(array);
for(int u = 0; u < array.length;u++)
System.out.println(" "+array[u]);
}
}
// Output :
The Size of array1 is 5
The Size of array2 is 6
The 4th element in array4
Fetching elements using for loop
1
2
3
4
5
6
Fetching elements from array using forEach
1
2
3
4
5
6
Modify 3rd ELement in array
1
2
9
4
5
6
Sort the Elements
1
2
4
5
6
9