Arrays in Java | Declaration, Example

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.

In short, an array in java is a collection of values of similar data type, stored in the contiguous memory location, sharing a common name, and distinguished by an element’s index.

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.

Features of Arrays in Java


The main features (or properties) of arrays in java are as follows:

1. An array in Java is a sequence of variables with a similar data type. The variables are called elements or components of the array that contain values of the same type.

2. The elements of an array can be either primitive data types or reference types (including itself array type).

3. Elements in Java array are always numbered from 0 to (n – 1) where n is the individual elements in the array.

4. The position of an element in an array is called index of element or subscript. The main intention of starting at 0 position is to make Java arrays follow the same convention as that of C and C++.

The index of the first element in every array is always zero and is sometimes called zeroth element.
[adinserter block=”5″]
5. The elements in the array are ordered or arranged in contiguous memory locations.

6. Arrays are objects in Java. Therefore, they can hold reference variables of other objects.

7. Arrays are created dynamically during runtime in Java.

8. They are dynamic, created on the heap memory.

9. The length of an array is its number of elements. It is set when the array is created and it cannot be changed. That is, the length of an array is fixed once the size of an array is created. Therefore, an array is not resizable.

10. Arrays may be assigned to variables of the Object type.

11. Any method of Object class can be called on the array.

12. Array objects implement Cloneable and Serializable interfaces.

13. An exception named ArrayIndexOutOfBoundsException will be thrown when property 3 is violated.

14. Arrays in Java can be duplicated with Object.clone() method.

15. They can be verified for equality with Arrays.equals() method.

Types of Arrays in Java


Generally, arrays are categorized into two forms that are as :

  1. Single dimensional arrays (or 1D array called one-dimensional array)
  2. 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:

Arrays in Java

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[0], x[1], x[2], x[3], . . . . . . . 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.
[adinserter block=”2″]
Consider the above figure. Each index position creates a different location in the memory. For example, x[0] holds a position at the memory address 3020, x[1] 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[ ]; // reference to array of ints.
float average[ ]; // reference to array of floats.
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.

In other simple words, declaring an array does not create an array or allocates memory space for its elements. Java compiler simply creates an object reference.


Note:

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[5]; // It can store five elements of integer type in an array. 5 is the length or size of array.
2) double[ ] myList = new double[10]; // 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.

Creating an array object in Java with example

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[5]; // 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.


This tutorial has covered all the important points related to arrays in Java and their declaration with the help of syntax and examples. Hope that you will have understood the basic concepts of arrays. In the next, we will learn how to initialize an array in Java with various examples.
Thanks for reading!!!

⇐ Prev Next ⇒