Page Stats
Visitor: 287
Java - Arrays
An array is a collection of homogeneous (similar type) elements.
Some important points about arrays:
- Arrays are always stored in continuous memory allocation.
- An array can store multiple values which can be referenced by a single name followed by an index inside a square bracket.
- Array index is a number starting from 0, will be increased by 1, till the maximum specified array size.
- Array index cannot be negative
- An array can be an integer, character or floating data type can be initialized only once at declaration time.
Arrays can be categorized into 2 categories:
- One Dimensional Array or 1D-Array
- Two Dimensional Array or 2D-Array
One Dimensional Array
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 [100]; or int []a = new int[100];

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]); } } }
Enter 10 numbers: 1 2 3 4 5 6 7 8 9 10
Input numbers are: 1 2 3 4 5 6 7 8 9 10
Input numbers are: 1 2 3 4 5 6 7 8 9 10
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 list is: 10 20 30 40 50
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