How to use Array in Java

Java Array

 
An array is a collection of elements of the same data type, stored in a contiguous memory location. Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value.
 

Features of Array

  1.  In Java, all arrays are dynamically allocated.
  2. Since arrays are objects in Java, we can find their length using member length. This is different from C/C++ where we find length using sizeof function.
  3. A Java array variable can also be declared like other variables with [] after the data type.
  4. The variables in the array are ordered and each has an index beginning from 0.
  5. Java array can also be used as a static field, a local variable or a method parameter.
  6. The size of an array must be specified by an int value and not long or short.
  7. The direct superclass of an array type is Object.

Shortcomings of Java 

  1.  Every array type implements the interfaces Cloneable and java.io.Serializable.
  2. The size of an Array can not be increased or decreased dynamically. 
  3. Array Class doesn't have an add or remove methods in Java 
  4. Arrays Suffer from the issue of memory wastage.
  5. To delete an element in an array we need to traverse throughout the array so this will reduce performance. 
  6. Arrays in java only support primitive data types. 

Types of Array

 

1. One-Dimensional Array 

 
This is a type of array which is arranged in the form of rows only i.e. all the elements are stored can only be visualized in a linear format/ 1D figure
 
 
  1. import java.util.Arrays;  
  2. import static java.lang.System.out;  
  3. public class Csharpcorner {  
  4.  public static void main(String[] args) {  
  5.   int demo[] = {  
  6.    10,  
  7.    20,  
  8.    15,  
  9.    22,  
  10.    35  
  11.   };  
  12.   out.println("Integer Array as List: " +  
  13.    Arrays.asList(demo));  
  14.  }  
  15. }  
In the above code, we are creating a 1D array named  demo.
 

2. Two-Dimensional Array

 
This is a type of array which is arranged in the form of rows and columns i.e. all the elements stored can be visualized as a Matrix or in 2D figure
 
   
  1. import static java.lang.System.out;  
  2. import java.util.Arrays;  
  3. public class Csharpcorner {  
  4.  public static void main(String[] args) {  
  5.   int demo[][] = {  
  6.    {  
  7.     2,  
  8.     7,  
  9.     9  
  10.    },  
  11.    {  
  12.     3,  
  13.     6,  
  14.     1  
  15.    },  
  16.    {  
  17.     7,  
  18.     4,  
  19.     2  
  20.    }  
  21.   };  
  22.   for (int i = 0; i < 3; i++) {  
  23.    for (int j = 0; j < 3; j++)  
  24.     out.print(demo[i][j] + " ");  
  25.    out.println();  
  26.   }  
  27.  }  
  28. }  
 In the above code, we are creating a 2D array named demo.
 

3. Multi-Dimensional / N-Dimensional Array 

 
This is a type of array which is arranged in the form of  (N-C) rows and C columns, where N is the dimension of array and C is the number of columns i.e all the elements stored can be visualized as (N-C) x C dimensional matrix or in an N-dimensional figure
 
 
  1. import java.util.Arrays;  
  2. import static java.lang.System.out;  
  3. public class Csharpcorner {  
  4.  public static void main(String[] args) {  
  5.   int demo[][][] = {  
  6.    {  
  7.     {  
  8.      1,  
  9.      -2,  
  10.      3  
  11.     }, {  
  12.      2,  
  13.      3,  
  14.      4  
  15.     }  
  16.    },  
  17.    {  
  18.     {  
  19.      -4, -569  
  20.     },  
  21.     {  
  22.      1  
  23.     },  
  24.     {  
  25.      2,  
  26.      3  
  27.     }  
  28.    }  
  29.   };  
  30.   for (int[][] array2D: demo) {  
  31.    for (int[] array1D: array2D) {  
  32.     for (int item: array1D) {  
  33.      out.println(item);  
  34.     }  
  35.    }  
  36.   }  
  37.  }  
  38. }  
In the above code, we are creating a 3D array named demo.
 

java.util.Arrays

 
array class is part of a java utility library, which comes pre-installed and pre-built as part of JDK (Java Development Environment).
A constructor can be used to create empty java arrays of various dimensions. 
  1. import java.util.Arrays;  
  2. public class Csharpcorner {  
  3.  public static void main(String[] args) {  
  4.   int[] arr = new int[5];  
  5.   int[][] arr = new int[5][5];  
  6.   int[][][] arr = new int[5][5][5];  
  7.  }  
  8. }   
The above code demonstrates how we use a constructor to create 1D, 2D, and 3D Arrays
 

Array Methods

 

1. Arrays.asList()

 
Syntax
 
static <T> List<T> asList(T… a) 
 
This method returns a fixed-size list backed by the specified Arrays.
  1. import java.util.Arrays;  
  2. import static java.lang.System.out;  
  3. public class Csharpcorner {  
  4.  public static void main(String[] args) {  
  5.   int demo[] = {  
  6.    10,  
  7.    20,  
  8.    15,  
  9.    22,  
  10.    35  
  11.   };  
  12.   out.println("Integer Array as List: " +  
  13.    Arrays.asList(demo));  
  14.  }  
  15. }   
 In the above code, we will be getting a list type of result that is java.util.Arrays will get converted to java.util.List
 

2. Arrays.binarySearch()

 
Syntax
 
1. static int binarySearch(elementToBeSearched)
 
These methods search for the specified element in the array with the help of the Binary Search algorithm. 
 
2. static <T> int binarySearch(T[] a, int fromIndex, int toIndex, T key, Comparator<T> c)
 
This method searches a range of the specified array for the specified object using the binary search algorithm. 
  1. import java.util.Arrays;  
  2. public class Csharpcorner {  
  3.  public static void main(String[] args) {  
  4.   int demo[] = {  
  5.    10,  
  6.    15,  
  7.    20,  
  8.    22,  
  9.    35  
  10.   };  
  11.   int Key = 22;  
  12.   int loc = Arrays.binarySearch(demo, Key)  
  13.   int loc1 = Arrays.binarySearch(demo, 13, Key)  
  14.  }  
  15. }   
In the above code, we are using the binary search algorithm to search for 22, and the location of the element will be stored in the variable "loc". To demonstrate the use of the second version of binarySearch() we use variable "loc1", which will perform the search between on elements of location 1 to location 3. i.e we will get the output of loc=3 and loc1=-4 (loc1=-4 because we have specified the range to be between 1 and 3, had it be 1 to 4 we would have got the answer to be loc1=3)
 

3. Arrays.compare()

 
Syntax
 
compare(array 1, array 2)
 
This method compares two arrays passed as parameters lexicographically. 
  1. import java.util.Arrays;  
  2. public class Csharpcorner {  
  3.  public static void main(String[] args) {  
  4.   int demo[] = {  
  5.    10,  
  6.    20,  
  7.    15,  
  8.    22,  
  9.    35  
  10.   };  
  11.   int demo1[] = {  
  12.    10,  
  13.    15,  
  14.    22  
  15.   };  
  16.   int out = Arrays.compare(demo, demo1);  
  17.  }  
  18. }   
In the above code, we are comparing if some of the elements of Array demo1 exist in the Array demo. Since every element of demo1 exists in demo, hence the output will be 1 i.e true.
 

4. Arrays.compareUnsighned()

 
Syntax
 
compareUnsigned(array 1, array 2)
 
This method compares two arrays lexicographically, numerically treating elements as unsigned. 
  1. import java.util.Arrays;  
  2. public class Csharpcorner {  
  3.  public static void main(String[] args) {  
  4.   int demo[] = {  
  5.    10,  
  6.    20,  
  7.    15,  
  8.    22,  
  9.    35  
  10.   };  
  11.   int demo1[] = {  
  12.    -10,  
  13.    -15,  
  14.    22  
  15.   };  
  16.   int out = Arrays.compareUnsigned(demo, demo1);  
  17.  }  
  18. }   
Note: the above method may or may not run on systems, as some JDK versions support this method and some don't
In the above code, we are comparing if some of the elements of Array demo1 exist in the Array demo. Since every element of demo1 exists in the demo, hence the output will be 1 i.e true
 

5. Arrays.copyOf()

 
Syntax
 
copyOf(originalArray, newLength)
 
This method copies the specified array, truncating or padding with the default value (if necessary) so the copy has the specified length.
  1. import java.util.Arrays;  
  2. public class Csharpcorner {  
  3.  public static void main(String[] args) {  
  4.   int demo[] = {  
  5.    10,  
  6.    20,  
  7.    15,  
  8.    22,  
  9.    35  
  10.   };  
  11.   int demo1[] = Arrays.copyOf(demo, 10);  
  12.  }  
  13. }   
In the above code, we will be increasing the size of new array to 10, since we are copying the elements of Array demo into Array demo1, and demo has only 5 elements, hence the value of next 5 elements will be zero, i.e demo1  will be {10, 20, 15, 22, 35, 0, 0, 0, 0, 0}
 

6. Arrays.copyOfRange()

 
Syntax
 
copyOfRange(originalArray, fromIndex, endIndex)
 
This method copies the specified range of the specified array into new Arrays. 
  1. import java.util.Arrays;  
  2. public class Csharpcorner {  
  3.  public static void main(String[] args) {  
  4.   int demo[] = {  
  5.    10,  
  6.    20,  
  7.    15,  
  8.    22,  
  9.    35  
  10.   };  
  11.   int demo1[] = Arrays.copyOfRange(demo, 13);  
  12.  }  
  13. }   
In the above code, we are creating a new Array demo1 which contains the array elements of location 1 to 3 from array demo.
 

7. Arrays.deepEquals()

 
Syntax
 
static boolean deepEquals(Object[] a1, Object[] a2)
 
This method returns true if the two specified arrays are deeply equal.
  1. import java.util.Arrays;  
  2. public class Csharpcorner {  
  3.  public static void main(String[] args) {  
  4.   int demo[] = {  
  5.    10,  
  6.    20,  
  7.    15,  
  8.    22,  
  9.    35  
  10.   };  
  11.   int demo1[] = {  
  12.    10,  
  13.    15,  
  14.    22  
  15.   };  
  16.   boolean ans = Arrays.deepEquals(demo, demo1);  
  17.  }  
  18. }   
In the above code, we are comparing if all the elements of Array demo1 exist in the Array demo. Since every element of demo1 does not exist in the demo, hence the output will be 1 i.e false
 

8. Arrays.deepHashCode()

 
Syntax
 
static int deepHashCode(Object[] a)
 
This method returns a hash code based on the “deep contents” of the specified Arrays.
  1. import java.util.Arrays;  
  2. public class Csharpcorner {  
  3.  public static void main(String[] args) {  
  4.   int demo[][] = {  
  5.    {  
  6.     10,  
  7.     20,  
  8.     15,  
  9.     22,  
  10.     35  
  11.    }  
  12.   };  
  13.   int ans = Arrays.deepHashCode(demo);  
  14.  }  
  15. }   
Note: the method will not work on a 1D array
 
In the above code, we will get a Hash Code based on the given array, hence the output will be 38475344 
 

9. Arrays.deepToString()

 
Syntax
 
static String deepToString(Object[] a)
 
This method returns a string representation of the “deep contents” of the specified Arrays.
  1. import java.util.Arrays;  
  2. import static java.lang.System.out;  
  3. public class Csharpcorner {  
  4.  public static void main(String[] args) {  
  5.   int demo[][] = {  
  6.    {  
  7.     10,  
  8.     20,  
  9.     15,  
  10.     22,  
  11.     35  
  12.    }  
  13.   };  
  14.   String ans;  
  15.   ans = Arrays.deepToString(demo);  
  16.   out.print(ans);  
  17.  }  
  18. }   
In the above code, the method will return a String object of array demo.
 

10. Arrays.equals()

 
Syntax
 
equals(array1, array2)
 
This method checks if both the arrays are equal or not. 
  1. import java.util.Arrays;  
  2. import static java.lang.System.out;  
  3. public class Csharpcorner {  
  4.  public static void main(String[] args) {  
  5.   int demo[] = {  
  6.    10,  
  7.    20,  
  8.    15,  
  9.    22,  
  10.    35  
  11.   };  
  12.   int demo1[] = {  
  13.    10,  
  14.    15,  
  15.    22  
  16.   };  
  17.   boolean ans;  
  18.   ans = Arrays.equals(demo, demo1);  
  19.   out.print(ans);  
  20.  }  
  21. }   
In the above code, we check whether both size and elements match in both the demo and demo1 array. Hence, the output will be false
 

11. Arrays.fill()

 
Syntax 
 
fill(originalArray, fillValue)
 
This method assigns this fillvalue to each index of these Arrays.
  1. import static java.lang.System.out;  
  2. import java.util.Arrays;  
  3. public class Csharpcorner {  
  4.  public static void main(String[] args) {  
  5.   int demo[] = {  
  6.    10,  
  7.    20,  
  8.    15,  
  9.    22,  
  10.    35  
  11.   };  
  12.   int intKey = 22;  
  13.   Arrays.fill(demo, intKey);  
  14.   out.print(Arrays.toString(demo));  
  15.  }  
  16. }   
In the above code, we will replace each element value with the fillValue i.e. 22
 

12. Arrays.hashCode()

 
Syntax
 
hashCode(originalArray)
 
This method returns an integer hashCode of this array instance.
  1. import static java.lang.System.out;  
  2. import java.util.Arrays;  
  3. public class Csharpcorner {  
  4.  public static void main(String[] args) {  
  5.   int demo[][] = {  
  6.    {  
  7.     10,  
  8.     20,  
  9.     15,  
  10.     22,  
  11.     35  
  12.    }  
  13.   };  
  14.   int ans = Arrays.hashCode(demo);  
  15.   out.print(ans);  
  16.  }  
  17. }   
In the above code, we will be generating a hash code based on the given array. Here the output will be 366712673.
 

13. Arrays.mismatch()

 
Syntax
 
mismatch(array1, array2)
 
This method finds and returns the index of the first unmatched element between the two specified arrays
  1. import java.util.Arrays;  
  2. import static java.lang.System.out;  
  3. public class Csharpcorner {  
  4.  public static void main(String[] args) {  
  5.   int demo[] = {  
  6.    10,  
  7.    20,  
  8.    15,  
  9.    22,  
  10.    35  
  11.   };  
  12.   int demo1[] = {  
  13.    10,  
  14.    15,  
  15.    22  
  16.   };  
  17.   int ans;  
  18.   ans = Arrays.mismatch(demo, demo1);  
  19.   out.print(ans);  
  20.  }  
  21. }   
Note: the above method may or may not run on systems, as some JDK versions support this method and some don't.
 
In the above code, the output will be 1 as demo1[1] and demo[0] does not match. 
 

14. Arrays.parallelSort()

 
Syntax
 
parallelSort(originalArray)
 
This method sorts the specified array using a parallel sort.
  1. import java.util.Arrays;  
  2. import static java.lang.System.out;  
  3. public class Csharpcorner {  
  4.  public static void main(String[] args) {  
  5.   int demo[] = {  
  6.    10,  
  7.    20,  
  8.    15,  
  9.    22,  
  10.    35  
  11.   };  
  12.   Arrays.parallelSort(demo);  
  13.   out.print(Arrays.toString(demo));  
  14.  }  
  15. }   
In the above code, we will get an array demo sorted in ascending order. 
 

15. Arrays.sort()

 
Syntax
 
1. sort(original arrayoriginalArray)
 
This method sorts the complete array in ascending order.
 
2.  sort(originalArray, fromIndex, endIndex)
 
This method sorts the specified range of array in ascending order.
 
3. static <T> void sort(T[] a, int fromIndex, int toIndex, Comparator< super T> c)
 
This method sorts the specified range of the specified array of objects according to the order induced by the specified comparator.
 
4. static <T> void sort(T[] a, Comparator< super T> c)
 
This method sorts the specified array of objects according to the order induced by the specified comparator. 
  1. import java.util.Arrays;  
  2. import static java.lang.System.out;  
  3. public class Csharpcorner {  
  4.  public static void main(String[] args) {  
  5.   int demo[] = {  
  6.    10,  
  7.    20,  
  8.    15,  
  9.    22,  
  10.    35  
  11.   };  
  12.   Arrays.sort(demo);  
  13.   out.print(Arrays.toString(demo));  
  14.   Arrays.sort(demo, 13);  
  15.   out.print(Arrays.toString(demo));  
  16.  }  
  17. }   
Note: the difference between parallelSort() and sort() is that Parallel Sort uses Fork/Join framework introduced in Java 7 to assign the sorting tasks to multiple threads available in the thread pool.
 
In the above code, we will get an array demo sorted in ascending order in both cases as in the second case we are sorting demo[1] to demo[3], which is the only part that is unsorted
 

16. Arrays.spliterator()

 
Syntax
 
1. spliterator(originalArray)
 
This method returns a Spliterator covering all of the specified Arrays.
 
2.  spliterator(originalArray, fromIndex, endIndex)
  1. import java.util.Arrays;  
  2. import java.util.Spliterator;  
  3. import static java.lang.System.out;  
  4. public class Csharpcorner {  
  5.  public static void main(String[] args) {  
  6.   int demo[] = {  
  7.    10,  
  8.    20,  
  9.    15,  
  10.    22,  
  11.    35  
  12.   };  
  13.   Spliterator.OfInt demo1 = Arrays.spliterator(demo);  
  14.   out.print(demo1);  
  15.   Spliterator.OfInt demo2 = Arrays.spliterator(demo, 13);  
  16.   out.print(demo2);  
  17.  }  
  18. }   
This method returns a Spliterator of the type of the array covering the specified range of the specified Arrays.
 
In the above code, we are first converting the whole of the array demo to spliterator and then converting a part of array demo to spliterator.
 

17. Arrays.stream() 

 
Syntax
 
stream(originalArray)
 
This method returns a sequential stream with the specified array as its source.
  1. import java.util.Arrays;  
  2. import static java.lang.System.out;  
  3. public class Csharpcorner {  
  4.  public static void main(String[] args) {  
  5.   int demo[] = {  
  6.    10,  
  7.    20,  
  8.    15,  
  9.    22,  
  10.    35  
  11.   };  
  12.   out.println("Integer Array: " +  
  13.    Arrays.stream(demo));  
  14.  }  
  15. }   
In the above, we are trying to get a sequential stream with the specified array demo as the source i.e. Integer Array: java.util.stream.IntPipeline$Head@6d06d69c as the output
 

18. Arrays.toString()

 
Syntax
 
toString(originalArray)
 
This method returns a string representation of the contents of these Arrays. The string representation consists of a list of the array’s elements, enclosed in square brackets (“[]”). Adjacent elements are separated by the characters a comma followed by a space. Elements are converted to strings as by String.valueOf() function. 
  1. import static java.lang.System.out;  
  2. import java.util.Arrays;  
  3. public class Csharpcorner {  
  4.  public static void main(String[] args) {  
  5.   int demo[] = {  
  6.    10,  
  7.    20,  
  8.    15,  
  9.    22,  
  10.    35  
  11.   };  
  12.   out.println("Integer Array: " +  
  13.    Arrays.toString(demo));  
  14.  }  
  15. }   
In the above, we are converting java.util.Arrays to java.lang.String, i.e. converting to String from Array
 

Conclusion

 
In the article, we learned about Array, features of Array, Shortcomings of Array, Types of Arrays, Array Methods and how to use the Array Class and methods using Java.
                                                              
                                                                              Next tutorial in this series>> Java String