In this java tutorial, you will learn everything about the data structure called arrays. With the aid of simple and interesting examples, you will understand how to manipulate arrays by declaring, initializing, and accessing variables from arrays.
The array is the simplest and most basic kind of data structure in java. A data structure as its name suggests is a particular structure in which data is stored in a memory. It is obvious that an organized memory works efficiently. So in java, there are a few ways we can store data, it can be stored linearly or stacked or in a tree structure.
An array is a linear data structure that stores a finite set of elements of the same data type in contiguous memory. Arrays in java use indexes for storing and retrieving elements and it always stores homogenous data.
This is what an array looks like. Here the array is able to store six pieces of data with an index starting from zero to five. So the length of this array is 6 and is always fixed.
We have learned from previous tutorials how to declare a variable in java. Array declaration in java is also similar to that but with few add-ons.An array variable holds multiple items of the same type. The general syntax of an array declaration is :
data_type[] array_name;
Where,
data_type represents the array type and can be any primitive data type like int, char, float, string, etc, or any java object.
array_name is the name of the array variable and it can be anything as per naming conventions;
[] is the special symbol which denotes the said variable is an array.
String[] colors;
For Example:
Here, colors is an array of type string.
Array declarations in java can also take the forms below :
String []colors; or
String colors[];
Declaring a variable doesn’t mean that the array has been allocated in the memory. It just tells the compiler that the declared variable is an array. So let’s understand how arrays are allocated in java. The syntax is :
data_type[] array_name = new data_type[array_size];
Example:
String[] colors = new String[7] ;
Here we have declared an array named colors
and allocated them in the memory with the help of the new
keyword and the size is mentioned as 7
. The allocation of arrays starts with a 'null
' and consequently the last element of the series will be stored at a[size -1]
. In our example, the first element of the array will be allocated at colors[0]
and the last element will be allotted at colors[6]
. Here we can say that the array length or size is 7
and is fixed.
The same declaration and allocation can be written in another form as shown below:
String[] colors
colors = new String[7] ;
So we have seen how to declare and allocate an array. Now let's see how to initialize the array with elements. Initialization can be done in two ways;
Java provides the facility to initialize an array at the time of declaration itself. This can be done by listing the elements inside a curly bracket followed by commas. The array initialization syntax is:
data_type[] array_name = {value_1st_element,value_2nd_element,3rd.....};
For instance,
String[] colors = {"VIOLET", "INDIGO", "BLUE", "GREEN","YELLOW", "ORANGE", "RED"};
When you observe the above example, you might notice that the size of the array is not mentioned. Here, the compiler automatically considers the size of the array by counting the number of elements the array is initialized with. In this case, the length of the array is 7 as seven colors are contained in the array.
Another way you can initialize an array is by using the index number. The memory location is always associated with a number called index number which helps in easy allocation and retrieval of the array elements. For instance,
//String array declaration
String[] colors = new String[7] ;
// Array initialization
colors[0] = “VIOLET”;
colors[1] = “INDIGO”;
colors[2] = “BLUE”;
colors[3] = “GREEN”;
colors[4] = “YELLOW”;
colors[5] = “ORANGE”;
colors[6] = “RED”;
A Single Dimensional Array after initialization can be best visualized as follows.
Now it's time to discuss how to access array elements in java. Array elements can be accessed in two ways:
While initializing we have seen how indexing works in java. Similarly to retrieve elements of an array we can use the same indexing technique which follows the syntax as below:
array_name[index_number];
See the below example:
class ArrayRainbow{
public static void main(String[] args) {
String[] colors = {"VIOLET", "INDIGO", "BLUE", "GREEN","YELLOW", "ORANGE", "RED"};
System.out.println("Accessing Elements of Array:");
System.out.println("Element at index of 0: " + colors[0]);
System.out.println("Element at index of 2: " + colors[2]);
System.out.println("Element at index of 4: " + colors[4]);
System.out.println("Element at index of 6: " + colors[6]);
}
}
The output will be:
Output:
Accessing Elements of Array: Element at index of 0: VIOLET Element at index of 2: BLUE Element at index of 4: YELLOW Element at index of 6: RED
Now suppose your array contains 100 elements and you want to access all elements at once. How can you achieve that? Yes, here comes our loop for the rescue. We can use the loop to access and print all elements in an array at once as given in the below example.
class ArrayRainbow{
public static void main(String[] args) {
String[] colors = {"VIOLET", "INDIGO", "BLUE", "GREEN","YELLOW", "ORANGE", "RED"};
System.out.println("Accessing Elements of Array using for loop");
for(int i=0;i
The output will be:
Output:
Accessing Elements of Array using for loop
VIOLET
INDIGO
BLUE
GREEN
YELLOW
ORANGE
RED
The above example shows you how to loop through an array. You might notice the length attribute specified in the for loop. If not, in java the length or the size of the array says how many elements the array has and can be determined using the length attribute. The syntax is as follows:
array_name.length;
See the below example
class ArrayRainbow{
public static void main(String[] args) {
String[] colors = {"VIOLET", "INDIGO", "BLUE", "GREEN","YELLOW", "ORANGE", "RED"};
//size of the array
int len = colors.length;
System.out.println("Length of the array is "+len);
System.out.println("Accessing Elements of Array using for loop");
for(int i=0;i<=len;i++)
{
System.out.println(colors[i]);
}
}
The output will be:
Output:
Length of the array is 7
Accessing Elements of Array using for loop
VIOLET
INDIGO
BLUE
GREEN
YELLOWORANGE
RED Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 7 out of bounds for length 7at ArrayRainbow.main(ArrayRainbow.java:14)
In the above output, you can see an ArrayIndexOutOfBoundException. As its name indicates, this occurs when you search for an element which is out of the index limit of the given array. The mistake happens when you forget to consider the fact that array indexing always starts with 0 and ends at n-1. In the above example the for loop checks for an element at 7th position though the array index bounds at 6th position.
Java provides another better way to loop through each element in an array. This method is considered as the simplest and hassle-free way to traverse through each element of an array. Why? Because it doesn’t require the counter(length attribute) and there is no chance for any index outbound exception to occur. The syntax is :
for (datatype variable_name : array_name) {
...
}
The above example can be modified as :
class ArrayRainbow{
public static void main(String[] args) {
String[] colors = {"VIOLET", "INDIGO", "BLUE", "GREEN","YELLOW", "ORANGE", "RED"};
for (String c : colors){
System.out.println(c);
}
}
}
The output will be:
Output:
VIOLET INDIGO BLUE GREEN YELLOW ORANGE RED
Suppose you want to change an array element at a specific position to some other. Is it possible in java? Absolutely possible. Here also make use of the index method and re-initialize it with your desired value. See below program:
class ArrayRainbow{
public static void main(String[] args) {
String[] colors = {"VIOLET", "INDIGO", "BLUE", "GREEN","YELLOW", "ORANGE", "RED"};
colors[2]="BLACK";
colors[4]="WHITE";
for (String c : colors){
System.out.println(c);
}
}
}
Output:
VIOLET INDIGO BLACK GREEN WHITE ORANGE RED
So far we were discussing on manipulating a single-dimensional array. Generally, an array with more than one row and one column is termed a multidimensional array. Since each element in a multidimensional array is an array itself, we can say that a multi-dimensional array is an array of arrays. It can be a two-dimensional array or a three-dimensional array or an n-dimensional array. So let’s discuss a two-dimensional array to understand how a multidimensional array works. A two-dimensional array comprises rows and columns, just like a matrix. It can be considered as a multidimensional array.
The declaration statement has two consecutive indices, one to represent the number of rows and the other to give the number of columns, as shown:
data_type[][] array_name = new data_type[row] [column];
int[][] table= new int[2][3];
Here, the table
is a 2-dimensional array that holds 6 integer values in 2 rows and 3 columns. While declaring two-dimensional arrays both row size and column size must be enclosed in square brackets. The allocation of each element will be as :
Initialization can be done during declaration and it takes the form
data_type[row] [column] array_name = {{value_1st_element,value_2nd_element,3rd.....},{.........}};
for instance, int[2][3] table ={ {10,20,30},{40,50,60} }
Two Dimensional Arrays after initialization can be best visualized as follows.
To explore more on multidimensional programs visit java programs.