This article (Java Array) is the continuation of our Java Article series. If you have missed our previous articles, read them all at Java category Archive.
(Java) Array definition
The named set of values of same type stored in continuous memory location is called Array. This is old definition that I have read in C. But in java array is treated as object or data structure which contain indexed fix number of values. In java members of array are called elements and all elements of arrays are of same type.
I will first write a line of code to define array as example and then proceed explanation.
int x[]={3,5,8,9,23};
This line code does every thing declaration, instantiation and initialisation.
This statement declare and instantiates an array x of type int
. It also initialise array with five elements. In the array x, 3 is in 0th index, 5 is in 1st index and so on. These elements are accessed using index in square brackets after array name like x[0] means 3 and x[4] means 23.
Advantages of java array:
Array is fastest and most native way of storing multiple data items under a single variable name. It is highly optimised and we can expect very fast program using array.
We can randomly access any elements of array.
Disadvantages:
Size of array is fixed and we can not grow this at run time. It means we have to specify size of the array at the time of instantiation. Here size of array refers to numbers elements in array.
Types of array
Java Arrays are of two types. These are single dimensional array and multi dimensional array.
Let’s have look at various valid ways that can be used to declare array in java.
- data_type arrayName[]=new data_type[size];
Example:int x[]=new int[5];
This line define an array of type integer with 5 elements. - data_type[] arrayName={value1,value2,value3,…,valuen};
Exampleint[] x={3,2,4,6,9};
- data_type []arrayName= new data_type[]{value1,value2,value3,…,valuen};
Example:int x= new int[]{3,2,4,6,9};
Foreach loop with array:
From version 1.5 java introduced a new loop named foreach loop to access array elements without using index variable. This loop is also called enhanced for loop.
Lets have a look at example code for enhanced for loop.
public static void main(String[] args) { int x[]={23,33,43,53,63}; for(int i:x) { System.out.println(i); } }
It’s output will be:
Practice this code snippet at your machine and run. If you successfully get the desired output, you rock. If there is any error that you are confused or I made some mistake, please let me know using comment below.