Arrays in Java

Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value. An array is a collection of similar data types. An array is a container object that holds values of a homogenous type.

arrays-index-diagram

Arrays are also known as static/fixed data structure because the size of an array must be specified at the time of its declaration. Once defined, the size of an array is fixed and cannot increase to accommodate more elements.

An array could be either primitive or object/reference type. Arrays get memory in heap area. Array in java is index-based, the first element of the array is stored at the 0 index.

Characteristics of Array:
  • It is always indexed. The index begins from 0.
  • An array is a collection of similar data types.
  • Arrays occupy a contiguous memory location.

Arrays also follow declarations and assignments like any other variable.

Declaration and Assignment of Arrays in java

Declaration: Both of the declarations are valid, the first one most preferred one

dataType[] variableName;

dataType variableName[];

Actual Examples :

int[ ] arr;
char[ ] arr;
short[ ] arr;
long[ ] arr;

Assignment:

//creates an empty array named arrayA of integer type whose size is 5.

int[] arrayA = new int[5];

or

//creates an array named arrayB whose elements are given.

int[] arrayB = {3,33,32,29,9};

Types of Arrays in Java

There are two types of arrays present in java

  • Single Dimension Arrays
  • Multi-Dimensional Arrays

One dimensional Array in java:

A one-dimensional array is, essentially, a list of like-typed variables.

Below Images shows how the values are stored in 1D arrays in java

arrays-index-diagram

In the above image, we can access the values using a single index, and storing the values in arrays is also done using a single index. One dimensional array will have only one index.

For example, If I want to access the element at 2nd index than I can write code like arrayA[2] and it will fetch the value to store a value we might need to use like arrayA[2] = 10 The values will be updated if any values are existing, or set if no value is present.

Multi dimensional Array in Java:

Multi-dimensional arrays hold the values in table format, and values will be aligned like rows and columns

To access any element present in the arrays we need to provide row number and column numbers, both starts from 0.

multi-dimensional-array-java

If we consider the above array as arrayM, then to access the value 90, we need to provide the rows and columns like arrayM[2][3]

Multi-dimensional arrays will be helpful when we are handling matrix kind of data.

Methods and Operations on Arrays in java

Assigning elements to the array :

We can assign elements to each index position in an array ranging from 0 to N-1, where N is the size of the array. In our case, the index numbers will range from 0 to 4 in the below example as the size is 5.

public class ArrayExample {
	public static void main(String[] args) {
	    int[] arrayA = new int[5];
	    arrayA[0] = 20;
	    arrayA[1] = 33;
	    arrayA[2] = 12;
	    arrayA[3] = 99;
	    System.out.println(arrayA[4]);
	}
}

The above program will store 20 and 33 in the 0th and 1st index position respectively in the array numbers. By default, all the positions from 0 to 4 have default value 0 stored.

Assignment During Creation :

Elements of an array can also be assigned at the same time when declaring the array. The format for doing so is as follows:

public class ArrayExample {
	public static void main(String[] args) {
	    int arrayB[]={2,6,9,4,8};
	    System.out.println(arrayB[2]);
	}
}

In the above example, the size of the array is automatically decided by the number of elements passed

Accessing element of an array :

After storing elements in an array, we may require to retrieve those elements at some point to time for calculations or in an expression for evaluation. This can be done again with the help of index number.

Not only just accessing elements, we can also perfom some operations using the elements like below.

public static void main(String[] args) {
	    int[] arrayA = new int[5];
	    arrayA[0] = 20;
	    arrayA[1] = 33;
	    arrayA[2] = 12;
	    arrayA[3] = 99;
	    System.out.println("Value at 3rd index " +arrayA[3]);
	    System.out.println("sum of index 1 and 2 " +arrayA[1] + arrayA[2]);
	    arrayA[4] = arrayA[0] * arrayA[2];
	    System.out.println("Value at 4th index " +arrayA[3]);
	}

output-of-arrays-java

Size of an Array :

We can get the size of an array using length property present in arrays. This is useful when we have not declared array with size, I mean when the array is formed using other means.

Size of the array is about number of cells allocated in memory, so it does not care about how many cells have user given values.

public class ArrayExample {
	public static void main(String[] args) {
	    int[] arrayA = new int[5];
	    arrayA[0] = 20;
	    arrayA[1] = 33;
	    System.out.println("Size of the array :" +arrayA.length);
	}
}

size-of-array-java

Fetch all the elements of an Array:

We can fetch all the values from an array rather than fetching the elements one by one. We can use for-loop and enhanced-for loop for this purpose.

Fetching elements using for Loop : We need to get the size of an array to iterate over the array, we can get the size using length property. we would be using the loop variable for iterating through the index of the array

public static void main(String[] args) {
	    int[] arrayA = new int[5];
	    arrayA[0] = 20;
	    arrayA[1] = 33;
	    for (int i = 0; i < arrayA.length; i++) {
	        System.out.println(arrayA[i]);
	    }
	}

for-loop-array-iterateYou can zeros because we have not assigned any values for index 2,3,4

enhanced for-loop / for-each loop: We can use for-each loop to iterate over the array without using any loop variables or without using the size of an array. for-each loop internally verifies whether it has reached to end of array or not on each iteration.

public static void main(String[] args) {
	    int[] arrayA = new int[5];
	    arrayA[0] = 20;
	    arrayA[1] = 33;
	    for (int item : arrayA) {
	        System.out.println(item);
	    }
	}

for-each-loop-java

What happens if we try to access an element outside the array size?

Compiler throws ArrayIndexOutOfBoundsException to indicate that array has been accessed with an index which is not available in the current array. The index is either negative or greater than or equal to the size of the array.

public static void main(String[] args) {
	    int[] arrayA = new int[5];
	    arrayA[0] = 20;
	    arrayA[1] = 33;
	    // max index is 4
	    System.out.println("Value at 7th index :" +arrayA[7]);
	}

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 7 at aaaaaa.ArrayExample.main(ArrayExample.java:9)

Jagged Array in Java

Jagged arrays in java are arrays containing arrays of different length.

Jagged array is an array of arrays (multi-dimensional array) such that members of the second dimensions can be of different sizes, i.e., we can create 2-D arrays but with a variable number of columns in each row. These type of arrays are also known as Jagged arrays. Jagged arrays are also known as Ragged arrays in Java.

We can create Jagged arrays like other arrays. If the elements of the array are known to us, we can declare and initialize the array in one step like below :

int[][] myArray = {{12},{32,12,38},{14,6},{3}};

jagged-arrays-java

Here, we have created one Jagged array of four elements. Each element is an array of integers. First element is {12} second element is {32, 12, 38}, third element is {14, 6}, and the fourth element is {3}.

In the above case, we know the elements of the array. So, it becomes easier for us to create the array. We need to declare the jagged array and initialize later if we do not know the elements which are going to be present.

public static void main(String args[])  
{ int[][] myArray = new int[3][]; myArray[0] = new int[]{1,2,3,4}; myArray[1] = new int[]{5,6}; myArray[2] = new int[]{7}; }

Accessing Jagged arrays:
public static void main(String[] args) {
	int jaggedArray[][] = {{1, 2, 3}, {4, 5}, {6, 8, 9}};
	for (int i = 0; i < jaggedArray.length; i++) {
	    System.out.println("Elements stored in position " + i);
	    for (int j = 0; j < jaggedArray[i].length; j++) {
	        System.out.print(" " + jaggedArray[i][j]);
	    }
	    System.out.println(" ");
	}
}

Anonymous Array in Java

Array without having any name is called Anonymous Array.

  • An array without name is known as anonymous array in java.
  • As the array do not have any name so it can be used only once.
  • Anonymous array is passed as an argument of method.
  • Anonymous array is created and initialized in the same line.
  • The main object of anonymous arrays is , it is created only for instant use.

A sample program is given below which shows that how 1D and 2D anonymous array can be created and used in java. In this program I have just created, initialized and passed two anonymous arrays in a method.

In print() method I am printing the elements of the arrays. If you find any difficulty to understand the program then you can comment below and ask your queries.

class AnonymousArray {
	static void print(int a[]) {
	    for (int i = 0; i < a.length; ++i)
	    System.out.print(a[i] + " ");
	}
	static void print(int a[][]) {
	    for (int i = 0; i < a.length; ++i) {
	        for (int j = 0; j < a[i].length; ++j)
	        System.out.println(a[i][j] + " ");
	    }
	}
	public static void main(String...s) {
	    //1d anonymous array 
	    print(new int[] {10, 20, 30, 40 });
	    System.out.println("n");
	    //2d anonymous array 
	    print(new int[][] {{10, 20}, {30, 40}, {50, 60} });
	}
}

Copy Java Arrays

Object.clone():

Object class provides clone() method and since array in java is also an Object, you can use this method to achieve full array copy. This method will not suit you if you want partial copy of the array.

        String[] names = {"Alex", "Brian", "Charles", "David"};
	    
	    // Use arr.clone() method - Recommended
	    String[] cloneOfNames = names.clone();
	    for (String string : cloneOfNames) {
	        System.out.println(string);
	    }

System.arraycopy():

System class arraycopy() is the best way to do partial copy of an array. It provides you an easy way to specify the total number of elements to copy and the source and destination array index positions.

For example System.arraycopy(source, 3, destination, 2, 5) will copy 5 elements from source to destination, beginning from 3rd index of source to 2nd index of destination.

        String[] names = {"Alex", "Brian", "Charles", "David"};
// Use Arrays.copyOf() method - Most readable String[] copyOfNames = Arrays.copyOf(names, names.length); for (String string : copyOfNames) { System.out.println(string); }

Arrays.copyOf():

If you want to copy first few elements of an array or full copy of array, you can use this method. Obviously it’s not versatile like System.arraycopy() but it’s also not confusing and easy to use.

        String[] names = {"Alex", "Brian", "Charles", "David"};
	    //Using System.arraycopy() method - Equally efficient but less readable
	    String[] copyOfNames2 = new String[names.length];
	    System.arraycopy(names, 0, copyOfNames2, 0, copyOfNames2.length);
	    for (String string : copyOfNames2) {
	        System.out.println(string);
	    }

Arrays.copyOfRange():

If you want few elements of an array to be copied, where starting index is not 0, you can use this method to copy partial array.

        String[] names = {"Alex", "Brian", "Charles", "David"};
	    //used names.length to get last number
	    String[] copyRanges = Arrays.copyOfRange(names, 0, names.length);
	    for (String string : copyRanges) {
	        System.out.println(string);
	    }

Accepting and returning Arrays from methods

Just like any other variables we can also accept and return arrays from methods.

public class ArrayExample {
	public static void main(String args[])  
	{ 
	    int arr[] = {1, 2, 7, 5, 4}; 
	    // passing array to method m1 
	    sumArray(arr); 
	    createArray(5, 3);
	} 
	//methods accepts array
	public static void sumArray(int[] arr)  
	{ 
	    // getting sum of array values 
	    int sum = 0; 
	    for (int i = 0; i < arr.length; i++) 
	        sum+=arr[i]; 
	    System.out.println("sum of array values : " + sum); 
	}
	//method return array
	public static int[] createArray(int elementValue, int numberOfElements)  
	{ 
	    // getting sum of array values 
	    int[] newArray = new int[numberOfElements]; 
	    for (int i = 0; i < numberOfElements; i++) {
	        newArray[i] = elementValue;
	    }
	    return newArray;
	}
}

Find the minimum and maximum values in an array

Sometimes you may need to find the minimum or maximum value in a Java array. Java does not have any built-in functions for finding minimum and maximum value, so I will show you how to code that yourself.

Minimum Value:
// Method for getting the minimum value
public static int getMinimum(int[] inputArray){ int minValue = inputArray[0]; for(int i=1;i<inputArray.length;i++){ if(inputArray[i] < minValue){ minValue = inputArray[i]; } } return minValue;
}

Maximum Value:
// Method for getting the maximum value

public static int getMaximum(int[] inputArray){ int maxValue = inputArray[0]; for(int i=1;i < inputArray.length;i++){ if(inputArray[i] > maxValue){ maxValue = inputArray[i]; } } return maxValue; }

Converting Arrays to Strings With Arrays.toString()

You can convert an Java array of primitive types to a String using the toString() method present in Arrays class. Here is an example of how to convert an array of int to a String using Arrays.toString():

If you try to invoke .toString() method from Object, it still gives Memory reference address but not the Elements
public class ArrayExample {
	public static void main(String args[])  
	{ 
	    int arr[] = {1, 2, 7, 5, 4}; 
	    for(int i=0; i < arr.length; i++){
	        arr[i] = 10 - i;
	    }
	    System.out.println("Using Arrays.toString() : " +Arrays.toString(arr));
	    System.out.println("Using toString() from Object class : " +arr.toString());
	} 
}

tostring-mehod-arrays

Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions