In Java, an array is a collection of homogeneous (similar type) elements. Array is useful when we want to store many values in a single variable.
Some important points about arrays:
Arrays can be categorized into 2 categories:
A one dimensional array is one directional array, which contain only one single row and multiple columns. One-dimensional array can be declared as follows:
int []a; a = new int [5]; or int []a = new int[5];
Example 1: WAP to input 10 numbers in 1D-Array and print them.
package arrays1d; import java.util.Scanner; public class Arrays1d { public static void main(String[] args) { int a[] = new int[10], i; Scanner scan = new Scanner(System.in); System.out.println("Enter 10 numbers: "); for(i=0;i<=9;i++) { a[i] = scan.nextInt(); } System.out.println("Input numbers are:"); for(i=0;i<=9;i++) { System.out.println(""+a[i]); } } }
1D-Array can be initialize as follows:
int a[] = { 1, 2, 3 };
Example 2: WAP to initialize array elements.
package arrays1d; public class Arrays1d { public static void main(String[] args) { int i; int a[] = {10,20,30,40,50}; System.out.println("Array list is:"); for(i=0;i<=4;i++) { System.out.println(a[i]); } } }
Array methods:
Array Length: To find array length
int a = array.length;
Array copy: To copy one array elements into another array
int a[] = { 1, 2, 3 }; int b[]; b=a; // copy element of a into b
Array sort:
Arrays.sort (array_variable_name); // java.util