Java Array is a container that can hold a fixed number of values of the same type. The values can be of the primitive type like int, short, byte, or it can be an object like String, Integer etc.

Java Array

  • Despite the fact that array can hold primitive type and object, array itself is an object in java heap, even if it is declared to hold primitive type data.
  • We need to specify the type of values at the time of declaring the array.
  • Array size needs to be provided at the time of initialization.
  • Java Arrays is the utility class that provides a lot of useful methods to work with arrays.
  • We can access array elements using integer index.
  • We can traverse through array elements using java for loop or java forEach loop.
  • Array can be one dimensional as well as multidimensional.
  • ArrayIndexOutOfBoundsException exception is raised when we try to access array element by specifying index value larger than the size of array.
  • List implementations such as ArrayList is backed by array. There are few utility methods to convert list to array and vice versa.
  • There are utility methods to search for an element in the array or to sort an array. We will look into these through example programs in later section of this tutorial.
  • java-array (1)

Let’s have a look at some important points about array through programs.

Array Declaration in Java

An Array can be declared by stating the type of data that array will hold (primitive or object) followed by the square bracket and variable name.
An array can be one dimensional or it can be multidimensional. Multidimensional arrays are in fact arrays of arrays.

  1. Declaring an array of primitive type of data (one dimensional):
    
    int[] integers;  // Recommended way of declaring an array
    int  integers[]; // Legal but not recommended
    
  2. Declaring an array of object type (one dimensional):
    
    String[] strings; // Recommended
    String strings[];  // not Recommended
    
  3. Declaring multidimensional array:
    
    int[][] integers; // Two dimensional array
    String[][][] strings; // Three dimensional array
    

When we are declaring an array it’s recommended that we put square bracket immediately after the declared type.

Java initialize array

We can initialize an array using new keyword or using shortcut syntax, which creates and initialize array at the same time.

Creating an array using new keyword means we are creating an array object in java heap and to create an object java needs to know how much space to allocate on the heap for that object. So we need to specify the size of the array at the time of initialization.

java-initialize-array

  1. Initializing one dimensional array:
    
    int[] integers; // declaration
    integers  =  new int[5]; // Initializing an array of primitive type with size 5
    int[] integers = new int[5]; // declaration and initialization in one line
    String[] strings; // declaration
    strings = new String[5]; // initializing an array of type String object with size 5
    String[] strings = new String[5]; // declaration and initialization in one line
    
  2. Initializing multidimensional array:
    
    int[][] intArr = new int[4][5];
    // multidimensional array initialization with only leftmost dimension
    int[][] intArr = new int[2][];
    intArr [0] = new int[2];
    intArr [1] = new int[3]; // complete initialization is required before we use the array
    
  3. Initializing an array using shortcut syntax:
    
    int[] intArr = {1,2,3};
    String[] strings = {"one", "two", "three"};
    int[][] intArr2 = {{1, 2}, {1, 2, 3}};
    

    If you notice above, the two dimensional array intArr2 is not a symmetric matrix. It’s because a multidimensional array in java is actually an array of array. For complete explanation, refer Two Dimensional Array in Java.

  4. Invalid ways to initialize an array: Here are some invalid ways to initialize an array.
    
    int[] a = new int[]; // invalid because size is not provided
    int[][] aa = new int[][5]; // invalid because leftmost dimension value is not provided
    
  5. Non recommended way to initialize an array: Here are some other variations of initializing arrays in java but they are strongly discouraged to avoid confusion.
    
    int[] integers[] = new int[4][5];
    int integers[][] = new int[5][];
    

Accessing Array Elements

  • Array elements can be accessed by its index and it always start with the 0 (zero).
  • Array object have public variable called length, which gives the number of elements in the array.
  • We can process or traverse array elements using for or foreach loop.

Let’s have look at the below example program for accessing array elements in java.


package com.journaldev.examples;
public class JavaArrayExample {
	public static void main(String[] args) {
		// initializing an array
		int[] integers = {1, 2, 3, 4, 5};
		String[] strings = {"one", "two", "three", "four", "five"};
		// using for loop to access elements
		System.out.println("Printing integer array using for loop :");
		for (int i = 0; i<integers.length; i++) {
			System.out.println(integers[i]);
		}
		System.out.println("Printing string array using for loop :");
		for (int i = 0; i<strings.length; i++) {
			System.out.println(strings[i]);
		}
		// using foreach loop for traversing through array
		System.out.println("Printing integer array using foreach loop :");
		for (int i : integers) {
			System.out.println(i);
		}
		System.out.println("Printing string array using foreach loop :");
		for (String s : strings) {
			System.out.println(s);
		}
	}
}

Now let’s look at an example of printing two-dimensional array using nested for loops.


package com.journaldev.examples;
public class TwoDimensionalArrayExample {
	public static void main(String[] args) {
		// initializing an array
		int[][] integers = { { 1, 2, 3 }, { 4, 5, 6 } };
		for (int i = 0; i < integers.length; i++) {
			for (int j = 0; j < integers[i].length; j++) {
				System.out.print(integers[i][j]);
				System.out.print(" ");
			}
			System.out.println();
		}
	}
}

What is ArrayIndexOutOfBoundsException?

Sometimes we try to access element outside the array size; for example if we have an array of size 10 and if we try to access 11th element then compiler will throw ArrayIndexOutOfBoundsException.

Let’s have a look at the below example program.


package com.journaldev.examples;
public class ArrayIndexOutOfBoundExample {
	public static void main(String[] args) {
		// declaring and initializing an array
		int[] a = new int[2];
		a[0] = 1;
		a[1] = 2;
		System.out.println(a[2]);
	}
}

Output of above program is:


Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
	at com.journaldev.examples.ArrayIndexOutOfBoundExample.main(ArrayIndexOutOfBoundExample.java:18)

Converting Array to List and Vice Versa


package com.journaldev.examples;
import java.util.Arrays;
import java.util.List;
public class ArrayConversionExample {
	public static void main(String[] args) {
		// initializing an array
		String[] strings = {"one", "two", "three", "four", "five"};
		//Converting array to list
		List<String> list = Arrays.asList(strings);
		System.out.println("Array to List : "+list);
		//Converting list to array
		String[] strings2 = list.toArray(new String[list.size()]);
		System.out.println("List to Array :");
		for (String string : strings2) {
			System.out.println(string);
		}
	}
}

Output of above program is:


Array to List : [one, two, three, four, five]
List to Array :
one
two
three
four
five

Java Sort Array

Arrays can be sorted by using java.util.Arrays sort method which sorts the given array into an ascending order. Below is a simple program for sorting arrays.


package com.journaldev.examples;
import java.util.Arrays;
public class ArraysSortExample {
	public static void main(String[] args) {
		// initializing an array of Character
		char[] chars = {'B', 'D', 'C', 'A', 'E'};
		// sorting array of Character
		Arrays.sort(chars);
		System.out.print("Sorted Characters : ");
		for (char character : chars) {
			System.out.print(character+" ");
		}
		// initializing an array of Integer
		int[] integers = {5, 2, 1, 4, 3};
		// sorting array of Integer
		Arrays.sort(integers);
		System.out.print("nSorted Integers : ");
		for (int i : integers) {
			System.out.print(i+" ");
		}
	}
}

Output of above program is:


Sorted Characters : A B C D E
Sorted Integers : 1 2 3 4 5

Searching for element in Java Array

java.util.Arrays provides binarySearch method which uses binary search algorithm to search specified value from the given array. Below is a simple program for searching element in an array using binary search. The array must be sorted prior to making this call. If it is not sorted, the results are undefined. If the array contains multiple elements with the specified value, there is no guarantee which one will be found.


package com.journaldev.examples;
import java.util.Arrays;
public class ArraysBinarySearchExample {
	public static void main(String[] args) {
		// Searching a value from array of integer
		int[] integers = { 5, 2, 1, 4, 3, 9, 6, 8, 7, 10 };
		int index = Arrays.binarySearch(integers, 2);
		if (index >= 0) {
			System.out.println("Element is found at the index :" + index);
		} else {
			System.out.println("Element is not found");
		}
		// Searching a value from array of integer with specific range
		int fromIndex = 2;
		int toIndex = 7;
		int index2 = Arrays.binarySearch(integers, fromIndex, toIndex, 9);
		if (index2 >= 0) {
			System.out.println("Element is found at the index :" + index2);
		} else {
			System.out.println("Element is not found");
		}
	}
}

Output of above program is:


Element is found at the index :1
Element is found at the index :5

Java Copy Array

Object class provides clone() method and since an 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 a partial copy of the array. Below is a simple program for copying arrays in java.


package com.journaldev.examples;
public class CopyingArrayExample {
	public static void main(String[] args) {
		// initialing an array
		int[] integers = {1, 2, 3, 4, 5};
		String[] strings = {"one", "two", "three", "four", "five"};
		//Copying Arrays
		int[] copyIntegers = integers.clone();
		System.out.println("Copy of Integer array :");
		for (int i : copyIntegers) {
			System.out.println(i);
		}
		String[] copyStrings = strings.clone();
		System.out.println("Copy of String array :");
		for (String string : copyStrings) {
			System.out.println(string);
		}
		//Copying two dimensional array
		int[][] arr = { { 1, 2, 3 }, { 4, 5, 6 } };
		int[][] copyArr = arr.clone();
		System.out.println("Copy of two dimensional Integer array :");
		for (int i = 0; i < copyArr.length; i++) {
			for (int j = 0; j < copyArr[i].length; j++) {
				System.out.print(copyArr[i][j]);
				System.out.print(" ");
			}
			System.out.println();
		}
	}
}

There are many other ways to copy the array in java. Please refer java copy array to learn other ways.

Add elements to Array

There is no shortcut method to add elements to an array in java. But as a programmer, we can write one. Here I am providing a utility method that we can use to add elements to an array.


package com.journaldev.examples;
import java.util.Arrays;
public class ArrayAddElementExample {
	public static void main(String[] args) {
		//initializing one array
		int[] a1 = {1, 2, 3, 4, 5};
		//element to be added
		int i = 6;
		//initializing second array
		int[] a2 = new int[a1.length+1];
		//copy first array into second
		System.arraycopy(a1, 0, a2, 0, a1.length);
		//add element to second array
		a2[a2.length-1] = i;
		System.out.println("Old Array: "+Arrays.toString(a1));
		System.out.println("New Array: "+Arrays.toString(a2));
	}
}

Output of the above program is:


Old Array: [1, 2, 3, 4, 5]
New Array: [1, 2, 3, 4, 5, 6]

Remove element from Array

Below is a simple program to remove element from array.


package com.journaldev.examples;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class RemoveElementFromArrayExample {
	public static void main(String[] args) {
		// initializing array
		String[] strings = {"one", "two", "three", "four", "five"};
		System.out.println("Array Before Removing element : "+Arrays.toString(strings));
		List<String> list = new ArrayList<>();
		String elementTobeRemoved = "four";
		for (String string : strings) {
			if (!string.equals(elementTobeRemoved)) {
				list.add(string);
			}
		}
		System.out.println("Array After Removing element : "+Arrays.toString(list.toArray(new String[list.size()])));
	}
}

Output of the above program is:


Array Before Removing element : [one, two, three, four, five]
Array After Removing element : [one, two, three, five]

That’s all for Java Array tutorial, I hope nothing important got missed here.

Reference: Oracle Documentation

By admin

Leave a Reply

%d bloggers like this: