HelloKoding

Practical coding guides

Java Array Examples

Array is a collection of similar data type elements which are stored in contiguous physical memory locations and identified by index

In Java, the size of the array is fixed after creation. You can declare an array of integers as below

int[] arr;

Array creation and initialization

  • In one line
int[] arr = {1, 2, 3};
  • In multiple lines
int[] arr = new int[3];
arr[0] = 1;
arr[1] = 2;
arr[2] = 3;

Array properties and methods

  • Get array length
int[] arr = {1, 2, 3};
int N = arr.length;
  • Clone an array
int[] arr = {1, 2, 3};
int[] clonedArr = arr.clone();
  • Array traversal
int[] arr = {1, 2, 3};
for(int i = 0; i < arr.length; i++) {
    System.out.println(arr[i]);
}
int[] arr = {1, 2, 3};
for(int ele : arr) {
    System.out.println(ele);
}

Array sorting, conversion and aggregation

Sorting

  • Sort an array in ascending order
int[] arr = {1, 2, 3};
Arrays.sort(arr);
  • Sort an array in descending order
int[] arr = {1, 2, 3};
arr = Arrays.stream(arr).boxed().sorted(Comparator.reverseOrder()).mapToInt(Integer::intValue).toArray();
Integer[] arr = {1, 2, 3};
Arrays.sort(arr, Collections.reverseOrder());

Conversion

  • Convert String array to int array
String[] strs = {"1", "2", "3"};
int[] arr = Arrays.stream(strs).mapToInt(Integer::parseInt).toArray();
  • String join int / long / float / double array
int[] arr = {1, 2, 3};
String str = Arrays.stream(arr).mapToObj(String::valueOf).collect(Collectors.joining(","));
  • Print array
int[] arr = {1, 2, 3};
System.out.println(Arrays.toString(arr));

Aggregation

  • Sum of an array
int[] arr = {1, 2, 3};
int sum = Arrays.stream(arr).sum();
Integer[] arr = {1, 2, 3};
int sum = Arrays.stream(arr).mapToInt(Integer::intValue).sum();
  • Average of an array
int[] arr = {1, 2, 3};
double avg = Arrays.stream(arr).average().getAsDouble();
  • Min of an array
int[] arr = {1, 2, 3};
int min = Arrays.stream(arr).min().getAsInt();
  • Max of an array
int[] arr = {1, 2, 3};
int max = Arrays.stream(arr).max().getAsInt();
Follow HelloKoding