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.
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.
- Declaring an array of primitive type of data (one dimensional):
1234int[] integers; // Recommended way of declaring an arrayint integers[]; // Legal but not recommended - Declaring an array of object type (one dimensional):
1234String[] strings; // RecommendedString strings[]; // not Recommended - Declaring multidimensional array:
1234int[][] integers; // Two dimensional arrayString[][][] 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.
- Initializing one dimensional array:
12345678int[] integers; // declarationintegers = new int[5]; // Initializing an array of primitive type with size 5int[] integers = new int[5]; // declaration and initialization in one lineString[] strings; // declarationstrings = new String[5]; // initializing an array of type String object with size 5String[] strings = new String[5]; // declaration and initialization in one line - Initializing multidimensional array:
1234567int[][] intArr = new int[4][5];// multidimensional array initialization with only leftmost dimensionint[][] intArr = new int[2][];intArr [0] = new int[2];intArr [1] = new int[3]; // complete initialization is required before we use the array - Initializing an array using shortcut syntax:
12345int[] 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. - Invalid ways to initialize an array: Here are some invalid ways to initialize an array.
1234int[] a = new int[]; // invalid because size is not providedint[][] aa = new int[][5]; // invalid because leftmost dimension value is not provided - 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.
1234int[] 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
orforeach
loop.
Let’s have look at the below example program for accessing array elements in java.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
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.
1 2 3 4 5 6 7 8 9 10 11 12 |
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:
1 2 3 4 |
<span style="color: #008000;"><strong><code> Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2 at com.journaldev.examples.ArrayIndexOutOfBoundExample.main(ArrayIndexOutOfBoundExample.java:18) </code></strong></span> |
Converting Array to List and Vice Versa
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
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:
1 2 3 4 5 6 7 8 9 |
<span style="color: #008000;"><strong><code> Array to List : [one, two, three, four, five] List to Array : one two three four five </code></strong></span> |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
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:
1 2 3 4 |
<span style="color: #008000;"><strong><code> Sorted Characters : A B C D E Sorted Integers : 1 2 3 4 5 </code></strong></span> |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
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:
1 2 3 4 |
<span style="color: #008000;"><strong><code> Element is found at the index :1 Element is found at the index :5 </code></strong></span> |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
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:
1 2 3 4 |
<span style="color: #008000;"><strong><code> Old Array: [1, 2, 3, 4, 5] New Array: [1, 2, 3, 4, 5, 6] </code></strong></span> |
Remove element from Array
Below is a simple program to remove element from array.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
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:
1 2 3 4 |
<span style="color: #008000;"><strong><code> Array Before Removing element : [one, two, three, four, five] Array After Removing element : [one, two, three, five] </code></strong></span> |
That’s all for Java Array tutorial, I hope nothing important got missed here.
Reference: Oracle Documentation