Arrays in Java

You must have already known from the datatype chapter itself that, how to store data in a variable like storing an integer in an int variable, a floating number in a double variable, and a character string in a String variable. Now the question is why do we want an array?

As the programs in java get advanced, we need to store the bulk data in a single data structure. So, a data structure is a structure that holds the data. An array is a data structure that contains the same type of data.

Unlike variables, which store only a single data, arrays can store many data items of the same data type. They are used to store data items in a contiguous memory location. In C and C++, pointers are used to work with an array. But in java, there are no pointers, and the arrays are also a bit different.

In java, we have an object which has a length field which denotes how many elements can be stored in the array. You can access the array element using their index, and they start with 0 and end at length-1. arrays-java-data-structures Each item in the array is known as an element, and we can access it by its integer index. When we initialize an array, we choose which type of data it can hold and how many elements it can hold.

The number of elements an array can store is mentioned in a field called length which cannot be changed once set.

Therefore, the field is often known as a constant field.

We initialize an array just like an instance of any other object, but we add opening and closing brackets next to the type of array. Let's take an example to initialize an array.

String[] names = new String[5]

In the above code, we have created an array called names to hold 5 String values. We can access each name i.e., element in the array by accessing its index.

The first element of the array is stored at index 0, and the last element is at index one less than the length of the array i.e., 4.

Now, let’s add names to the array:

names[0] = "Abhinab";
names[1] = "Kunu";
names[2] = "Ranjan";          
namesh[3] = "Mukesh";
names[4]= "Sumit";


String[]  names = {"Abhinab", "Kunu", "Ranjan", "Mukesh", "Sumit" };

Now let us know how to iterate over an array:

class UsingForLopp{
    public static void main(String[] args){
       String[]  names = {"Abhinab", "Kunu", "Ranjan", "Mukesh", "Sumit" };
       System.out.println("The names are mentioned below");
       for(int i=0; i<names.length; i++){

So, here is the output:

The names are mentioned below

You can use this same technique to loop over any primitive array, for example, integer, float, double.

Now, if we want to access the last element of the array dynamically then the code is as follow:

System.out.println("Last name is " + names[names.length – 1]);

Length is a property of the array to find out the total number of elements in an array. We used that property to find out the length of the array and subtracted one from it to find out the last element of the array.

Now let us make another array to hold the roll numbers for these names:

int[] NamesRollNumbers = new int[names.length];
NamesRollNumbers[0] = 1;
NamesRollNumbers[1] = 2;
NamesRollNumbers[2] = 3;
NamesRollNumbers[3] = 4;
NameswRollNumbers[4] = 5;

Now let us print out the names and their equivalent roll numbers using for loop:

for(int index = 0; index < names.length; index++){
 String name = names[index];
 System.out.printf("%s's roll number is %d\n", name, NamesRollNuumbers[index]);

The output is:

Abhinab’s roll number is 1
Kunu’s roll number is 2
Ranjan’s roll number is 3
Mukesh’s roll number is 4
Sumit’s roll number is 5

Now, look at this code:

public class Name{
     private String name;
     private int rollNumber;

     public String toString() {
       return String.format("Name: %s | Roll Number: (%d)-%d", name, rollNumber);

Here, we used format() method of the String class to map values.

Now let us create an array of type Name and add roll numbers to them in another way:

Name[] rollNumber = new Name[5];
rollNumber[0] = new Name("Abhinab", 1);
rollNumber[1] = new Name("Kunu", 2);
rollNumber[2] = new Name("Ranjan", 3);
rollNumber[3] = new Name("Mukesh", 4);
rollNumber[4] = new Name("Sumit", 5);

Now, let us try to print this:

for(int index = 0; index < names.length; index++) {
 Name name = rollNumber[index];
 System.out.println("Name " + index + " :- " + name);

The output is:

Name 0 :- 	Name: Abhinab | Roll Number: 1	
Name 1 :-   Name: Kunu | Roll Number: 2
Name 2 :-   Name: Ranjan | Roll Number: 3
Name 3 :-   Name: Mukesh | Roll Number: 4
Name 4 :-   Name: Sumit | Roll Number: 5

Type of arrays

One-Dimensional Array :

The general form of an one-dimensional array is:

type var-name[]; or type[] var-name;

The array declaration has two components: the type and the name. Type means the data type of each element that comprises the array. Example:

class oneDimensionalArray { 
    public static void main(String args[]) 
        int[] a; // one dimensional array declaration 
        a = new int[5]; // creating array of size 3 
        for (int i = 0; i < 5; i++) { 
            a[i] = 20; 

The output is:


Multi-Dimensional Array :

The general form of a multi-dimensional array is:

int[][] intArray = new int[5][10]; // a 2D array
int[][][] intArray = new int[5][10][5]; // a 3D array


class multiDimensional 
    public static void main(String args[]) 
        // declaring and initializing a 2D array 
        int arr[][] = { {1,2,3},{4,5,6},{7,8,9} }; 
        // printing the 2D array 
        for (int i=0; i< 3 ; i++) 
            for (int j=0; j < 3 ; j++) 
                System.out.print(arr[i][j] + " "); 

The output is:

1 2 3 
4 5 6
7 8 9

Common Useful Methods Used In Arrays

Declare an array

String[] aArray = new String[5];
String[] bArray = {"a","b","c", "d", "e"};
String[] cArray = new String[]{"a","b","c","d","e"};

Print an array

int[] intArray = { 1, 2, 3, 4, 5 };
String intArrayString = Arrays.toString(intArray);
System.out.println(intArray); // prints reference value
System.out.println(intArrayString);// prints [1, 2, 3, 4, 5]

Create ArrayList from array

String[] stringArray = { "a", "b", "c", "d", "e" };
ArrayList arrayList = new ArrayList<String>(Arrays.asList(stringArray));
System.out.println(arrayList);  // [a, b, c, d, e]

Check if an array contains a certain value

String[] stringArray = { "a", "b", "c", "d", "e" };
boolean b = Arrays.asList(stringArray).contains("a");
System.out.println(b); // true

Concatenate two arrays

int[] intArray = { 1, 2, 3, 4, 5 };
int[] intArray2 = { 6, 7, 8, 9, 10 };
int[] combinedIntArray = ArrayUtils.addAll(intArray, intArray2);

Convert Array to Set

Set<String> set = new HashSet<String>(Arrays.asList(stringArray));
System.out.println(set); // [d, e, b, c, a]

Reverse an array

int[] intArray = { 1, 2, 3, 4, 5 };
System.out.println(Arrays.toString(intArray)); // [5, 4, 3, 2, 1]

Remove element of an array

int[] intArray = { 1, 2, 3, 4, 5 };
int[] removed = ArrayUtils.removeElement(intArray, 3);//create a new array

Advantages of arrays in java

  • In using array, we can initialize and declare multiple data type values easily while declaring them as separate variables would be a difficult task.
  • There is no run-time overhead for the allocation and free of memory.
  • We get a feature RANDOM ACCESS OF ELEMENTS which means we don't need to iterate over the entire array to access a value. We can directly access it using the index.
  • It gives us fast sequential access because of contiguous memory allocation.
  • 2-Dimensional arrays are used to represent matrices.
  • Arrays can also be used to represent other data structures like stacks, queues, trees, graphs, linked lists, etc.

Disadvantages of arrays in java

  • We need to mention the size of the array in advance which is of a fixed length. That means, the size of the arrays once declared can’t be changed at runtime.
  • An array is static which means the memory which is allocated to the array cannot be increased or reduced.
  • Java treats arrays as objects because we use these arrays as a reference type. Because of this fact, we can not use == operator for comparison of arrays as == operator compares the references and not the values stored in the array.
    	int arr1[] = {1,2,3,4}
    	int arr2[] = {1,2,3,4}

    When we evaluate arr1==arr2, it results in FALSE. So, we cannot use equals method as it cannot compare data stored in arrays.

  • To delete an element in an array we need to traverse throughout the array which reduces the performance.
  • As we have to initialize and declare the size of the array in advance, there is a chance of memory wastage.

About Author

Myself KarthiQ, I am the author of this blog, I know ways to write a good article but some how I donot have the skills to make it to reach people, would you like help me to reach more people By sharing this Article in the social media.

Share this Article Facebook
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions