Array in Java is a container object that holds a group or collection of elements of a similar data type.
In other words, an array is a fixed-size data structure that is used to hold more than one value of the same data type.
It is generally used to store a group of elements (or values) or a collection of related data items that share a common name.
So, we can store a group of strings, a group of int values, or a group of float values in the array. But, we cannot store some int values or some float values in the array.
Elements of an array in java are stored in a contiguous memory location. When the memory space for an array is allocated, the array size must be given (or fixed) that represents the number of elements.
Once the size of an array is created, it cannot be changed further. That is, an array cannot expand or shrink if we need. Thus, we can store a fixed set of elements in an array.
Why do we need Arrays in Java?
So far, we have worked with variables that hold only one value at a time. For example, an integer variable can hold only one number and a string variable can hold a long string of text.
Let us assume a class contains 60 students and we want to store their roll numbers. The roll numbers will be integers so we will declare 60 separate variables for storing the roll numbers like this:
int rollNo; int rollNo1; int rollNo2; . . . int rollNo59;
Now we will need another 60 statements to store roll numbers in these variables. Even if you write 120 statements just to store the roll numbers of students, the resulting code will be unmanageable and clumsy.
In this situation, arrays come to the rescue. Using an array, we can declare a single variable that can hold all these 60 values. That is, an array variable of a type can hold as many values of that type as we want.
The advantage of using an array is that we can simplify programming by replacing many statements with just one or two statements and increasing understanding readability.
Types of Arrays in Java
Generally, arrays are categorized into two forms that are as :
- Single dimensional arrays (or 1D array called one-dimensional array)
- Multidimensional arrays (or 2D, 3D arrays)
In this tutorial, we will concentrate on the one-dimensional array, and in the further tutorial, we will discuss multi-dimensional array.
One dimensional Array (or Single dimensional Array) in Java
A one-dimensional array contains a list of variables of the same type and is accessed through a common name. Each variable in the array is called an array element.
Each element in the array is represented by an array name with its index or subscript enclosed in a square bracket [ ]. A single-dimensional array can have only one full row or full column of elements. Look at the figure below to explore more about array:
Here, the numbers enclosed in square brackets are called index values or subscripts to the array. The array would be written with index values like this: x, x, x, x, . . . . . . . x[n-1].
These numbers locate the position of elements within the array so that we can directly access elements from the position into an array.
Since an array is an index-based structure, the first element of the array is stored at the 0th index, 2nd element is stored on 1st index, and so on.
In Java, every array object holds space in the memory. Like int, float, char, elements of array list also take space in the memory as the memory address according to their separate data values.
Consider the above figure. Each index position creates a different location in the memory. For example, x holds a position at the memory address 3020, x holds a position at the memory address 3022, and so on.
Accessing of arrays is checked at runtime, an attempt to use an index that is less than zero or greater than or equal to the length of array generates an exception named IndexOutOfBoundException.
Array Variables Declaration in Java
Array stores multiple values of similar type in a single variable, instead of declaring individual variables, such as num0, num1, num2, and so on for each value.
To use a one-dimensional array in java program, we must declare a variable to reference the array with specifying the array’s element type. The general syntax for declaring an array variable in java comes in two forms:
Form1: elementType[ ] arrayname; Form2: elementType arrayname[ ];
Here, elementType represents data type that can be any primitive data type like int, char, float, Double, etc., String, or an object. arrayname represents an identifier. All elements in the array will have the same data type.
For example, the following code declares various array variables with different data types:
int month_days[ ]; // Declare an integer array variable. month_days can hold multiple int values. int number[ ]; float average[ ]; int[ ] counter; String[ ] name; // name can hold multiple references to String objects. int[ ] empId; Employe[ ] emp; // emp can hold multiple references to Employee objects.
In the following declaration of array variables, no array actually exists. In fact, the value of all array variables is set to null that represents an array with no value.
a) An array variable is a reference variable that points to an array object. The memory that is allocated to an array variable actually stores a reference to an array object. It does not actually store an array itself.
b) Strictly speaking, an array and an array variable are different, but most of the time the distinction can be neglected. Thus, it is all right to say, for simplicity, that month_days is an array, instead of stating that month_day is a reference variable that contains a reference to an array of multiple int values.
Creating an Array in Java
Unlike declaration of the primitive data type variable, the declaration of an array variable does not create any space in memory for the array. It creates only a memory space for the reference to an array.
If an array variable does not have a reference to an array, the value of the variable is null. We cannot assign values or data to an array unless it has already been created.
Now, let’s understand how to create an array object of a particular type?
In Java, an array is an object. Every object in java belongs to a class, so we can create an array object by using a new keyword and assign its reference to the variable.
The general syntax for the creation of array object is as follows:
arrayname = new datatype[arraySize];
In this syntax, arraySize specifies the number of elements in the array that we want to store in it. arrayname is an array variable that is linked to an array.
The above syntax does two things:
(1) It creates an array using new datatype[arraySize];
(2) It assigns the reference of the newly created array to the array variable arrayname.
Declaring an array variable, creating an array, and assigning the array object reference to the variable can be combined in one statement like this:
datatype[ ] arrayname = new datatype[arraySize]; Or, datatype arrayname[ ] = new datatype[arraySize];
Here is an example of such statements:
1) num = new int; // It can store five elements of integer type in an array. 5 is the length or size of array. 2) double[ ] myList = new double; // It can store 10 elements of double type.
Both statement one-dimensional arrays (linear). They declare array variables, num, and myList, creates an array of five and ten elements of int and double types and assigns their references to num and myList.
The number of elements (integer data) in the first array is 5 and in the second array, it is 10 (double data). That is, their size are 5 and 10. But they can add or delete elements dynamically.
Since each element in the num array is a variable of int type that needs 4 bytes in the memory, the whole array will take space 20 bytes in the memory, plus 4 bytes for the num variable to store the reference of array in the memory.
When an array is constructed like this, all elements of the array are initialized with a default value automatically.
Similarly, each element in the myList array is a variable of double type that needs 8 bytes in the memory, the whole array will take space 80 bytes in the memory, plus 8 bytes for the myList variable to store the reference of array in the memory.
Look at the below figure to understand better.
We can also declare an expression to specify the length of an array while creating an array:
int length = 10; int[ ] arr1 = new int[length]; // arr1 has 10 elements. int[ ] arr2 = new int[length * 2] // arr2 has 20 elements.
Since all arrays are objects in java, their references can be assigned to a reference variable of Object type. For example:
int sId[ ] = new int; // Create an array object. Object obj = sId[ ]; // valid assignment.
Here, we have a reference of an array in a reference variable of Object type. In this case, we need to cast it to an appropriate array type before accessing elements by index or assigning it to a new array reference variable. The general syntax is as follows:
int[ ] arr = (int[ ]) obj; // obj is a reference variable of Object type that holds a reference of int[ ].
Advantages of Arrays in Java
There are several advantages of arrays in Java. They are as follows:
1. The main advantage of array-based structure is that it organizes data in such a way that it can be easily manipulated.
2. We can access randomly nth element in an array at a constant time.
3. Arrays generally use less space because no variable needs to support navigation.
4. Arrays optimizes the code, thereby, we can retrieve or sort the data efficiently.
Disadvantages of Arrays in Java
There are many disadvantages of arrays in java that are as follows:
1. Since arrays are fixed in size, we can store only the fixed size of elements in the array.
2. Once the size of an array is created, it cannot be changed. That is, an array cannot expand or shrink at runtime. To solve this problem, Java has introduced the Collections framework which grows automatically.
3. We cannot store different kinds of elements in an array. For example, an array of an Employee class will store only Employee type objects. A primitive array of int will only store the values of int type.
Hope that this tutorial has covered all the important points related to arrays in java and their declaration with examples. I hope that you will have understood the basic concepts of arrays.
Thanks for reading!!!