Java Array Tutorial

The tutorial explains everything about Array in Java. Learn how to use Java Array methods and properties.

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. 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.           
  4. public class Csharpcorner   
  5. {       
  6.         public static void main(String[] args)       
  7.         {       
  8.             // Get the Array       
  9.             int demo[] = { 1020152235 };       
  10.           
  11.             // To convert the elements as List       
  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.         
  4. public class Csharpcorner {         
  5.     public static void main(String[] args)         
  6.     {         
  7.         // Get the Array         
  8.         int demo[][] = { {2,7,9},{3,6,1},{7,4,2} };        
  9.         
  10.         // To convert the elements as List         
  11.         for (int i=0; i< 3 ; i++)       
  12.         {       
  13.             for (int j=0; j < 3 ; j++)       
  14.                 out.print(demo[i][j] + " ");       
  15.        
  16.             out.println();       
  17.         }          
  18.     }         
  19. }     
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.           
  4. public class Csharpcorner   
  5. {       
  6.         public static void main(String[] args)       
  7.         {       
  8.             // Get the Array       
  9.             int demo[][][] = {{{1, -23}, {234}}, { {-4, -569}, {1}, {23}} };      
  10.           
  11.             // To convert the elements as List       
  12.             for (int[][] array2D: demo) {    
  13.                 for (int[] array1D: array2D) {    
  14.                     for(int item: array1D) {    
  15.                             out.println(item);    
  16.                     }    
  17.                 }    
  18.             }      
  19.         }       
  20. }    
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 the 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.     
  3. public class Csharpcorner {     
  4.     public static void main(String[] args)     
  5.     {     
  6.     
  7.         // 1D Array     
  8.         int[] arr = new int[5];   
  9.     
  10.        // 2D Array  
  11.        int[][] arr = new int[5][5];   
  12.     
  13.         // 3D Array  
  14.        int[][][] arr = new int[5][5][5];   
  15.   
  16.     }     
  17. }    
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.       
  4. public class Csharpcorner {       
  5.     public static void main(String[] args)       
  6.     {       
  7.         // Get the Array     
  8.         int demo[] = { 1020152235 };     
  9.       
  10.         // To convert the elements as List     
  11.         out.println("Integer Array as List: "    
  12.                            + Arrays.asList(demo));     
  13.     }       
  14. }   

 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 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.     
  3. public class Csharpcorner {     
  4.     public static void main(String[] args)     
  5.     {     
  6.        int demo[] = { 10, 15, 202235 };   
  7.     
  8.        int Key = 22;   
  9.     
  10.        int loc=Arrays.binarySearch(demo, Key)  
  11.   
  12.        int loc1=Arrays.binarySearch(demo, 13, Key)  
  13.     }     
  14. }    
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.     
  3. public class Csharpcorner {     
  4.     public static void main(String[] args)     
  5.     {     
  6.         int demo[] = { 1020152235 };   
  7.     
  8.         int demo1[] = { 101522 };  
  9.   
  10.         int out = Arrays.compare(demo, demo1);  
  11.     }     
  12. }    
In the above code, we are comparing if some of the elements of Array demo1 exists in 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.     
  3. public class Csharpcorner {     
  4.     public static void main(String[] args)     
  5.     {     
  6.         int demo[] = { 1020152235 };   
  7.     
  8.         int demo1[] = { -10, -1522 };  
  9.   
  10.         int out = Arrays.compareUnsigned(demo, demo1);  
  11.     }     
  12. }    
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 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.     
  3. public class Csharpcorner {     
  4.     public static void main(String[] args)     
  5.     {     
  6.         int demo[] = { 1020152235 };   
  7.     
  8.         int demo1[] = Arrays.copyOf(demo, 10);  
  9.     }     
  10. }    
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.       
  3. public class Csharpcorner {       
  4.     public static void main(String[] args)       
  5.     {       
  6.         int demo[] = { 1020152235 };     
  7.       
  8.         int demo1[] = Arrays.copyOfRange(demo, 13);    
  9.     }       
  10. }      
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.     
  3. public class Csharpcorner {     
  4.     public static void main(String[] args)     
  5.     {     
  6.         int demo[] = { 1020152235 };   
  7.     
  8.         int demo1[] = { 101522};  
  9.   
  10.         boolean ans = Arrays.deepEquals(demo, demo1);  
  11.     }     
  12. }    
In the above code, we are comparing if all the elements of Array demo1 exist in 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.     
  3. public class Csharpcorner {     
  4.     public static void main(String[] args)     
  5.     {     
  6.         int demo[][] = {{ 1020152235 }};   
  7.     
  8.         int ans = Arrays.deepHashCode(demo);  
  9.     }     
  10. }    
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.         
  4. public class Csharpcorner   
  5. {         
  6.     public static void main(String[] args)         
  7.     {         
  8.         int demo[][] = {{ 1020152235 }};       
  9.         
  10.         String ans;      
  11.         ans = Arrays.deepToString(demo);    
  12.         out.print(ans);    
  13.     }         
  14. }
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.         
  4. public class Csharpcorner   
  5. {         
  6.     public static void main(String[] args)         
  7.     {         
  8.         int demo[] = { 1020152235 };       
  9.         
  10.         int demo1[] = { 101522};    
  11.         boolean ans;      
  12.         ans = Arrays.equals(demo, demo1);    
  13.         out.print(ans);    
  14.     }         
  15. }  
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.         
  4. public class Csharpcorner   
  5. {         
  6.     public static void main(String[] args)         
  7.     {         
  8.         int demo[] = { 1020152235 };       
  9.         
  10.         int intKey = 22;     
  11.       
  12.         Arrays.fill(demo, intKey);     
  13.         out.print(Arrays.toString(demo));    
  14.     }         
  15. }
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.             
  4. public class Csharpcorner   
  5.  {         
  6.         public static void main(String[] args)         
  7.         {         
  8.             int demo[][] = {{ 1020152235 }};       
  9.             
  10.             int ans = Arrays.hashCode(demo);      
  11.             out.print(ans);    
  12.         }         
  13. }    
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.         
  4. public class Csharpcorner   
  5. {         
  6.     public static void main(String[] args)         
  7.     {         
  8.         int demo[] = { 1020152235 };    
  9.             
  10.         int demo1[] = { 101522};    
  11.         
  12.         int ans;      
  13.         ans = Arrays.mismatch(demo,demo1);    
  14.         out.print(ans);    
  15.     }         
  16. }   
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.         
  4. public class Csharpcorner   
  5. {         
  6.     public static void main(String[] args)         
  7.     {         
  8.         int demo[] = { 1020152235 };    
  9.             
  10.         Arrays.parallelSort(demo);    
  11.         out.print(Arrays.toString(demo));    
  12.     }         
  13. }   
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.         
  4. public class Csharpcorner     
  5. {         
  6.     public static void main(String[] args)         
  7.     {         
  8.         int demo[] = { 1020152235 };    
  9.             
  10.         Arrays.sort(demo);    
  11.         out.print(Arrays.toString(demo));    
  12.         Arrays.sort(demo, 13);    
  13.         out.print(Arrays.toString(demo));    
  14.     }         
  15. }   
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.        
  5. public class Csharpcorner     
  6. {         
  7.         public static void main(String[] args)         
  8.         {         
  9.             int demo[] = { 1020152235 };    
  10.                 
  11.             Spliterator.OfInt demo1= Arrays.spliterator(demo);    
  12.             out.print(demo1);    
  13.             Spliterator.OfInt demo2= Arrays.spliterator(demo,1,3);    
  14.             out.print(demo2);    
  15.         }         
  16.  }       
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.         
  4. public class Csharpcorner     
  5. {         
  6.     public static void main(String[] args)         
  7.     {         
  8.         int demo[] = { 1020152235 };    
  9.             
  10.         out.println("Integer Array: "    
  11.                            + Arrays.stream(demo));    
  12.     }         
  13. }  
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.             
  4. public class Csharpcorner     
  5.  {         
  6.         public static void main(String[] args)         
  7.         {         
  8.             int demo[] = { 1020152235 };    
  9.                 
  10.             out.println("Integer Array: "    
  11.                                + Arrays.toString(demo));    
  12.         }         
  13.  }   
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 learnt 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