How do you declare an array in Java?
Arrays are data types that store multiple values of a single type. An array is an object in Java itself and is created with new keyword.
The figure shows the schematic representation of an array in which 5 elements can be stored. This length of an array is always constant and can not be changed after the declaration.
The stored values themselves must always be of the same type. Permitted here are any primitive data types or objects. Even other arrays can be stored in an array. See also the section on multidimensional arrays below.
If the above array is to be e.g. to store int values, their declaration follows in the following way:
1 2 3 | int[] arr = new int[5]; |
It starts on the left with the name of the data type to be saved, followed by an opening and a closing square bracket. This together identifies the present array data type. After the then variable identifier, which has to comply with the usual conventions and the assignment operator, note the keyword new to create the array object. It is followed again by the data type with square brackets. Here, however, the length of the array, ie the number of memory locations, must be noted as a positive, integer value. A semicolon completes the expression.
As already mentioned above, the size of an array is basically not changeable. If the number of values ​​to be stored increases during the runtime of a program, this must be taken into account in the declaration either by declaring a sufficiently large array or by using another data type for storage, such as an ArrayList, from the beginning.
Conversely, memory spaces of an array can remain empty. During access, depending on the stored data type, either the default value or zero is used.
Incidentally, the parentheses can also be written after the variable identifier instead of after the type identifier.
1 2 3 | int arr[] = new int[5]; // not recommended |
However, this spelling is not recommended and you should prefer the notation of parentheses after the data type identifier, because only in this way a unique data type specification is present.
If an array without object formation is to be declared, the following notation is also possible:
1 2 3 | int[] numbers; |
The initialization of an array in Java
A newly created array is soon empty. His storage spaces still have to be occupied.
The individual entries of an array are numbered consecutively. One speaks of the index of the respective position. From the above scheme it can be seen that the counting of the indices starts at 0, so that an array of length 5 has the indices of 0-4.
The initialization of an array takes place by assigning the respective value to the special array position, which is called via the index.,
1 2 3 4 5 6 7 8 | int[] arr = new int[5]; arr[0] = 214; arr[1] = -27; arr[2] = 1456; arr[3] = 0; arr[4] = -640; |
As mentioned above, an array position may also remain empty. If this is the case, the default value of the respective data type is used when accessing the memory location.
If a newly formed array is to be assigned values immediately at the declaration, then an array can also be declared and initialized at the same time. This happens in the following way:
1 2 3 | int[] arr = {214, -27, 1456, 0, -640}; |
Attention! However, a new assignment of an existing array object is not possible in this way.
Access to the stored values of an array in Java
The values stored in an array can be accessed through the index. Referring to the example above, the value stored in the fourth digit (Index 3!) Is accessed by the following expression:
1 2 3 | int i = arr[3]; // 0 |
The following example summarizes what has been said so far. An array of length 5 is generated and occupied in a loop at each position with the value of the count index. The termination condition accesses the length of the array. It can be determined by its length property. The value stored at each position is then output to the console.
1 2 3 4 5 6 7 8 9 10 11 12 | public static void main(String[] args) { // Declare array of length 5 int[] numbers = new int[5]; int num=10; for(int i=0;i<numbers.length; i++) { numbers[i]=num*i; System.out.println("index:"+i+" --- value:"+numbers[i]); } } |
output:
Multi-Dimensional arrays in Java
Arrays can themselves contain other arrays. One then speaks of multidimensional arrays. The opposite shows the scheme of a two-dimensional array containing 3 5-length arrays, which can be declared in the following way.
1 2 3 | int[][] numbers= new int[3][5]; |
Theoretically, any memory depth is conceivable. But already three-dimensional arrays are not often found, since readability decreases rapidly with increasing memory depth.
In the above example, the stored arrays are the same size. However, multidimensional arrays can also store arrays of different sizes. Here is an example of a combined declaration and initialization of such an array:
1 2 3 | int[][] numbers= {{1,2,3}, {1,2,3,4}, {1,2,3,4,5}}; |
However, this is not recommended, as the risk of accessing invalid indexes is high and in this case an IndexOutOfBoundsException is thrown.
As with one-dimensional arrays, the values for multi-dimensional arrays are also accessed via the indices.
In the following example, the previously mentioned is summarized again slightly varied.
A two-dimensional array is declared and initialized with three string arrays, each containing four address data. The array at the third position (index 2) is then replaced by another one. In two nested loops, all content is finally read out. Note how within the inner loop, the index is used to access the arrays stored at each location.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | public static void main(String[] args) { String[][] personList = { { "Todd Mcpherson", "7282 Cursus St.", "Grenada" }, { "Christian Burke", "534-8718 Sed Av.", "Morocco" }, { "Guy Bird", "Ap #137-9027 Ac Ave", "Reunion" }}; String[] person = new String[3]; person[0] = "Edan Barker"; person[1] = "Ap #162-9422 Varius Road"; person[2] = "Chile"; personList[2]=person; for (int i = 0; i < personList.length; i++) { for (int j = 0; j < personList[i].length; j++) { System.out.println(personList[i][j]); } System.out.println(); } } |
Output:
Processing Arrays in Java
When processing array elements, we often use either for loop or foreach loop because all of the elements in an array are of the same type and the size of the array is known.
Example
Here is a complete example showing how to create, initialize, and process 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 | public static void main(String[] args) { double[] myList = {12.9, 12.9, 34.4, 32.5}; // Print all the array elements for (int i = 0; i < myList.length; i++) { System.out.println(myList[i] + " "); } // Summing all elements double total = 0; for (int i = 0; i < myList.length; i++) { total += myList[i]; } System.out.println("Total is " + total); // Finding the largest element double max = myList[0]; for (int i = 1; i < myList.length; i++) { if (myList[i] > max) max = myList[i]; } System.out.println("Max is " + max); } |
Output:
The foreach Loops in Java Arrays
JDK 1.5 introduced a new for loop known as foreach loop or enhanced for loop, which enables you to traverse the complete array sequentially without using an index variable.
Example
The following code displays all the elements in the array myList :
1 2 3 4 5 6 7 8 9 10 | public static void main(String[] args) { double[] myList = {12.9, 12.9, 34.4, 32.5}; // Print all the array elements for (double element: myList) { System.out.println(element); } } |
Output:
Passing Arrays to Methods in Java
Just as you can pass primitive type values to methods, you can also pass arrays to methods. For example, the following method displays the elements in an int array −
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | public class JavaExamples { public static void printArray(double[] array) { for (int i = 0; i < array.length; i++) { System.out.print(array[i] + " "); } } public static void main(String[] args) { double[] myList = {12.9, 12.9, 34.4, 32.5}; // Print all the array elements printArray(myList); } } |
Returning an Array from a Method in Java
A method may also return an array. For example, the following method returns an array that is the reversal of another array:
Example
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 | public class JavaExamples { public static int[] reverse() { int[] numbers = new int[5]; int i=0; while(i<numbers.length){ numbers[i]=i; i++; } return numbers; } public static void main(String[] args) { int[] myList=reverse(); // Print all the array elements for (int element: myList) { System.out.println(element); } } } |
The Arrays Class in Java
The java.util.Arrays class contains various static methods for sorting and searching arrays, comparing arrays, and filling array elements. These methods are overloaded for all primitive types.
Method – Description |
---|
public static int binarySearch(Object[] a, Object key) Searches the specified array of Object ( Byte, Int , double, etc.) for the specified value using the binary search algorithm. The array must be sorted prior to making this call. This returns index of the search key, if it is contained in the list; otherwise, it returns ( – (insertion point + 1)). |
public static boolean equals(long[] a, long[] a2) Returns true if the two specified arrays of longs are equal to one another. Two arrays are considered equal if both arrays contain the same number of elements, and all corresponding pairs of elements in the two arrays are equal. This returns true if the two arrays are equal. Same method could be used by all other primitive data types (Byte, short, Int, etc.) |
public static void fill(int[] a, int val) Assigns the specified int value to each element of the specified array of ints. The same method could be used by all other primitive data types (Byte, short, Int, etc.) |
public static void sort(Object[] a) Sorts the specified array of objects into an ascending order, according to the natural ordering of its elements. The same method could be used by all other primitive data types ( Byte, short, Int, etc.) |
Java Array Examples
Example 1: Program to Calculate Average Using Arrays
1 2 3 4 5 6 7 8 9 10 11 12 13 | public class Average { public static void main(String[] args) { double[] numArray = { 45.3, 67.5, -45.6, 20.34, 33.0, 45.6 }; double sum = 0.0; for (double num: numArray) { sum += num; } double average = sum / numArray.length; System.out.format("The average is: %.2f", average); } } |
Example 2: Find largest element in an array
1 2 3 4 5 6 7 8 9 10 11 12 13 | public class Largest { public static void main(String[] args) { double[] numArray = { 23.4, -34.5, 50.0, 33.5, 55.5, 43.7, 5.7, -66.5 }; double largest = numArray[0]; for (double num: numArray) { if(largest < num) largest = num; } System.out.format("Largest element = %.2f", largest); } } |
Example 3: Program to Add Two Matrices
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | public class AddMatrices { public static void main(String[] args) { int rows = 2, columns = 3; int[][] firstMatrix = { {2, 3, 4}, {5, 2, 3} }; int[][] secondMatrix = { {-4, 5, 3}, {5, 6, 3} }; // Adding Two matrices int[][] sum = new int[rows][columns]; for(int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { sum[i][j] = firstMatrix[i][j] + secondMatrix[i][j]; } } // Displaying the result System.out.println("Sum of two matrices is: "); for(int[] row : sum) { for (int column : row) { System.out.print(column + " "); } System.out.println(); } } } |
Example 4: Program to Multiply Two Matrices
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 | public class MultiplyMatrices { public static void main(String[] args) { int r1 = 2, c1 = 3; int r2 = 3, c2 = 2; int[][] firstMatrix = { {3, -2, 5}, {3, 0, 4} }; int[][] secondMatrix = { {2, 3}, {-9, 0}, {0, 4} }; // Mutliplying Two matrices int[][] product = new int[r1][c2]; for(int i = 0; i < r1; i++) { for (int j = 0; j < c2; j++) { for (int k = 0; k < c1; k++) { product[i][j] += firstMatrix[i][k] * secondMatrix[k][j]; } } } // Displaying the result System.out.println("Sum of two matrices is: "); for(int[] row : product) { for (int column : row) { System.out.print(column + " "); } System.out.println(); } } } |
Example 5: Print an Array using For loop
1 2 3 4 5 6 7 8 9 10 | public class Array { public static void main(String[] args) { int[] array = {1, 2, 3, 4, 5}; for (int element: array) { System.out.println(element); } } } |
Example 6: Print an Array using standard library Arrays
1 2 3 4 5 6 7 8 9 | import java.util.Arrays; public class Array { public static void main(String[] args) { int[] array = {1, 2, 3, 4, 5}; System.out.println(Arrays.toString(array)); } } |
Example 7: Print a Multi-dimenstional Array
1 2 3 4 5 6 7 8 9 | import java.util.Arrays; public class Array { public static void main(String[] args) { int[][] array = {{1, 2}, {3, 4}, {5, 6, 7}}; System.out.println(Arrays.deepToString(array)); } } |
Example 8: Concatenate Two Arrays using arraycopy
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | import java.util.Arrays; public class Concat { public static void main(String[] args) { int[] array1 = {1, 2, 3}; int[] array2 = {4, 5, 6}; int aLen = array1.length; int bLen = array2.length; int[] result = new int[aLen + bLen]; System.arraycopy(array1, 0, result, 0, aLen); System.arraycopy(array2, 0, result, aLen, bLen); System.out.println(Arrays.toString(result)); } } |
Example 9: Concatenate Two Arrays without using arraycopy
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | import java.util.Arrays; public class Concat { public static void main(String[] args) { int[] array1 = {1, 2, 3}; int[] array2 = {4, 5, 6}; int length = array1.length + array2.length; int[] result = new int[length]; int pos = 0; for (int element : array1) { result[pos] = element; pos++; } for (int element : array2) { result[pos] = element; pos++; } System.out.println(Arrays.toString(result)); } } |
Example 10: Check if Int Array contains a given value
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | public class Contains { public static void main(String[] args) { int[] num = {1, 2, 3, 4, 5}; int toFind = 3; boolean found = false; for (int n : num) { if (n == toFind) { found = true; break; } } if(found) System.out.println(toFind + " is found."); else System.out.println(toFind + " is not found."); } } |
Example 11: Check if array contains given value using Stream
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | import java.util.stream.IntStream; public class Contains { public static void main(String[] args) { int[] num = {1, 2, 3, 4, 5}; int toFind = 7; boolean found = IntStream.of(num).anyMatch(n -> n == toFind); if(found) System.out.println(toFind + " is found."); else System.out.println(toFind + " is not found."); } } |
Example 12: Check if array contains a given value for non-primitive types
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | import java.util.Arrays; public class Contains { public static void main(String[] args) { String[] strings = {"One", "Two", "Three", "Four", "Five"}; String toFind = "Four"; boolean found = Arrays.stream(strings).anyMatch(t -> t.equals(toFind)); if(found) System.out.println(toFind + " is found."); else System.out.println(toFind + " is not found."); } } |
Example 13: Convert list to array
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class ListArray { public static void main(String[] args) { List<String> list = new ArrayList<String>(); list.add("a"); list.add("b"); String[] array = new String[list.size()]; list.toArray(array); System.out.println(Arrays.toString(array)); } } |
Example 14: Convert Array to list
1 2 3 4 5 6 7 8 9 10 11 | import java.util.Arrays; import java.util.List; public class ArrayToList { public static void main(String[] args) { String[] array = {"a", "b"}; List<String> list = Arrays.asList(array); System.out.println(list); } } |
Example 15: Convert Array to Set
1 2 3 4 5 6 7 8 9 10 | import java.util.*; public class ArraySet { public static void main(String[] args) { String[] array = {"a", "b", "c"}; Set<String> set = new HashSet<>(Arrays.asList(array)); System.out.println("Set: " + set); } } |
Example 16: Convert Array to Set using stream
1 2 3 4 5 6 7 8 9 10 | import java.util.*; public class ArraySet { public static void main(String[] args) { String[] array = {"a", "b", "c"}; Set<String> set = new HashSet<>(Arrays.stream(array).collect(Collectors.toSet())); System.out.println("Set: " + set); } } |
Example 17: Convert Set to Array
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | import java.util.*; public class SetArray { public static void main(String[] args) { Set<String> set = new HashSet<>(); set.add("a"); set.add("b"); set.add("c"); String[] array = new String[set.size()]; set.toArray(array); System.out.println("Array: " + Arrays.toString(array)); } } |
Example 18: Convert Byte Array to Hex value
1 2 3 4 5 6 7 8 9 10 11 | public class ByteHex { public static void main(String[] args) { byte[] bytes = {10, 2, 15, 11}; for (byte b : bytes) { String st = String.format("%02X", b); System.out.print(st); } } } |
Example 19: Convert Byte Array to Hex value using byte operations
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | public class ByteHex { private final static char[] hexArray = "0123456789ABCDEF".toCharArray(); public static String bytesToHex(byte[] bytes) { char[] hexChars = new char[bytes.length * 2]; for ( int j = 0; j < bytes.length; j++ ) { int v = bytes[j] & 0xFF; hexChars[j * 2] = hexArray[v >>> 4]; hexChars[j * 2 + 1] = hexArray[v & 0x0F]; } return new String(hexChars); } public static void main(String[] args) { byte[] bytes = {10, 2, 15, 11}; String s = bytesToHex(bytes); System.out.println(s); } } |
Example 20: Convert File to byte[]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Arrays; public class FileByte { public static void main(String[] args) { String path = System.getProperty("user.dir") + "\\src\\test.txt"; try { byte[] encoded = Files.readAllBytes(Paths.get(path)); System.out.println(Arrays.toString(encoded)); } catch (IOException e) { } } } |
Example 21: Convert byte[] to File
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; public class ByteFile { public static void main(String[] args) { String path = System.getProperty("user.dir") + "\\src\\test.txt"; String finalPath = System.getProperty("user.dir") + "\\src\\final.txt"; try { byte[] encoded = Files.readAllBytes(Paths.get(path)); Files.write(Paths.get(finalPath), encoded); } catch (IOException e) { } } } |
Example 22: Sort ArrayList of Custom Objects By Property
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | import java.util.*; public class CustomObject { private String customProperty; public CustomObject(String property) { this.customProperty = property; } public String getCustomProperty() { return this.customProperty; } public static void main(String[] args) { ArrayList<Customobject> list = new ArrayList<>(); list.add(new CustomObject("Z")); list.add(new CustomObject("A")); list.add(new CustomObject("B")); list.add(new CustomObject("X")); list.add(new CustomObject("Aa")); list.sort((o1, o2) -> o1.getCustomProperty().compareTo(o2.getCustomProperty())); for (CustomObject obj : list) { System.out.println(obj.getCustomProperty()); } } } |