Previous | Home | Next |
An array is a data structure that stores a collection of homogeneous(same type) values. You can access each individual value of the array through an integer index.
For Example: If arr is an array of integers, then arr[i] is the ith integer in the array. You can declare an array variable by specifying the array type which is the element type followed by [] and the array variable name. Now we can delare an array variable arr as
int[] arr; //please prefer this one or int arr[];
Above statement only declares the variable arr. It doesn't intiailize the arr with an actual array, for that we have to use new operator to declare an array. For instance,
int[] arr = new int[50];
Above declaration creates an array of integer type which can accomodate 50 integers. In Java too, like other programming languages, the index of array starts from 0 to (length-1). In this case array enteries are numbered from 0 to 49. Also Java doesn’t allow you to specify the size of an empty array when declaring the array.
You always must explicitly set the size of the array with the new operator or by assigning a list of items to the array on creation. If you try to access the element arr[50] (or any other index outside the range 0 ..49), then your program will terminate with an “array index out of bounds” exception. As in other languages like C and C++ once you create an array, you cannot change its size.
Java can directly create an array object and supply initial values at the same time just like other languagaes. For e.g.
- int[] numbers = { 2, 3, 4, 5, 6, 7, 8 };
You do not call new when you declare an array using this approach.You can even initialize an anonymous array in java like the following one:
- new int[] { 11, 12, 13, 14, 15, 16, 17};
Above declaration allocates a new array and fills it with the values inside the braces and counts the number of initial values then sets the array size accordingly. You can use this syntax to reinitialize an array without creating a new variable.
Example
numbers = new int[] { 11, 12, 13, 14, 15, 16, 17 }; is a shorthand for int[] anonymousarr = { 11, 12, 13, 14, 15, 16, 17 }; numbers = anonymousarr;
Once an array is created you can access its elements throught its index values.For calculating the length of an array we use length() method viz. arrayname.length, gives the length of the array. Following code snippet shows the very same:
Java Tutorialslass ArrayAccess { public static void main(String[] args) { int[] numbers={2, 3, 4, 5, 6, 7, 8}; System.out.println("The elements of the array are :"); for(int i=0;i<numbers.length;i++) { System.out.println(a[i]); } } }
Here, we have use numbers. length to calculate the length of the array and a[i] gives the elements of the array.
Previous | Home | Next |