In Java, the data can be stored in various types of containers such as “Array” which can store data of multiple types. An array is sliced to delete the unused data consuming memory or to update the data. 

Moreover, this approach allows us to generate new data from the current data instead of including it repeatedly. For instance, getting the substring from a string array and combining it with another string, etc.

What is Array Slicing in Java?

Array Slicing” is the process of returning a subarray of the given array based on the array indexes.

Demonstration

Below is the sample demonstration for slicing an array:

Query

Assume that there is an array “x[ ] = {1, 2, 3, 4, 5}” containing the given elements indexed from x[0] to x[4]. 

Requirement

Slice an array from x[2] to x[4] indexes where “2” is the starting and “4” is the ending index.

Solution

The sliced array will be returned as “x[ ] = {3, 4, 5}”.

How to Slice an Array in Java?

An array in Java can be sliced using the following approaches:

  • Copying Elements to a New Array.
  • Arrays.copyOfRange()” Method.
  • Java 8 Stream.
  • arrayCopy()” Method.
  • Stream API.

Approach 1: Slice an Array in Java by Copying Elements to a New Array

In this approach, a separate new array is used to contain the copied sliced elements from the original array:

package jbArticles;
import java.util.Arrays;
public class Slicearray {
public static void main(String args[]) {
  int[] givenArray = {1, 2, 3, 4, 5};
  System.out.println("Given Array -> "+Arrays.toString(givenArray));
  int firstIndex = 1, lastIndex = 3;
  int[] arraySlice = new int[lastIndex - firstIndex];
  for (int i = 0; i < arraySlice.length; i++) {
    arraySlice[i] = givenArray[firstIndex + i];
  }
  System.out.println("Sliced Array -> "+Arrays.toString(arraySlice));
}
}

Code Explanation

  • Initialize an integer array containing the given elements and display it as a string via the “Arrays.toString()” method.
  • Now, specify the first and last indexes of the resultant sliced array from the given array.
  • It is such that only these elements will be sliced(the last index excluded).
  • After that, create a new integer array named “arraySlice” that assigns the size of the new array i.e., 2 in this case.
  • Apply the “for” loop to iterate the new array and append this array with elements at the “1” and “2” index of the original array.
  • Lastly, return the array as a string using the “Arrays.toString()” method.

Output

Important Consideration

Specifying an index that is not in the array i.e., exceeding the array index returns the “ArrayIndexOutOfBoundsException”, as demonstrated below:

Approach 2: Slice an Array in Java Using “Arrays.copyOfRange()” Method

The “Arrays.copyOfRange()” method copies the range of the given array into another array.

Syntax

static int[] copyOfRange(int[] def, int src, int dest)

Syntax Explanation

  • def” refers to the default array from which the range is copied.
  • src” represents the starting(inclusive) index of the range to copy.
  • dest” is the final(exclusive) index to copy.

Return Value

It gives a new array having the given range from the default array.

The below code uses this method to copy the range of starting and ending indexes and return a new sliced array based on that:

package jbArticles;
import java.util.Arrays;
public class Slicearray {
public static void main(String args[]) {    int[] givenArray = {1, 2, 3, 4, 5};   System.out.println("Given Array -> "+Arrays.toString(givenArray));
  int firstIndex = 1, lastIndex = 3;
  int[] arraySlice = Arrays.copyOfRange(givenArray, firstIndex, lastIndex);
  System.out.println("Sliced Array -> "+Arrays.toString(arraySlice));
}
}

Code Explanation

  • Initialize an integer array and return it as a string.
  • Define the indexes based on which the array elements need to be sliced.
  • Apply the “Arrays.copyOfRange()” method to copy the defined range of the start and end indexes from the original array.
  • These indexed elements(the last index excluded) are placed in a new array named “arraySlice” such that the array is sliced accordingly.
  • Finally, return the array as a string.

Output

Approach 3: Slice an Array in Java Using “Java 8 Stream”

The Java 8 “Streams” is used to slice an array by taking the target indexes of the sliced array and mapping these elements from the given array. After that, the mapped array is converted into an array:

package jbArticles;
import java.util.stream.IntStream;
import java.util.Arrays;
public class Slicearray {
public static void main(String args[]) {
  int[] givenArray = {1, 2, 3, 4, 5};
  System.out.println("Given Array -> "+Arrays.toString(givenArray));
  int firstIndex = 2, lastIndex = 4;
  int[] arraySlice = IntStream.range(firstIndex,  lastIndex).map(i->givenArray[i]).toArray();
  System.out.println("Sliced Array -> "+Arrays.toString(arraySlice));
}
}

Code Explanation

  • Recall the steps for defining an array and returning it as a string.
  • Specify the first and last indexes of the given array elements to be sliced.
  • Now, use the “Java 8 Stream” to map the specified range of indexes from the given array to the new mapped array “arraySlice”.
  • Return the mapped array as a string.

Output

Approach 4: Slice an Array in Java Using the “arrayCopy()” Method

This method copies a source array, at a target start position, to a destination at the given index. It is used to make a copy of the array and insert element(s) into it.

Syntax

public static void arraycopy(Object src, int sind, Object des, int destind, int len)

Syntax Explanation

  • src” indicates the source array.
  • sind” is the source array’s start index.
  • des” is the final array.
  • destind” is the start index of the target array.
  • len” is the item to copy from the default/source to the target array.

The following code uses this method to copy the required number of elements i.e., (string in this case) from the original array:

package jbArticles;
import java.util.Arrays;
public class Slicearray {
public static void main(String args[]) {
  String[] givenArray = {"Harry", "David", "Liam", "Paul"};
  System.out.println("Given Array -> "+Arrays.toString(givenArray));
  int firstIndex = 1, lastIndex = 2;
  String[] arraySlice = new String[lastIndex];
  System.arraycopy(givenArray, firstIndex, arraySlice, 0, lastIndex);
  System.out.println("Sliced Array -> "+Arrays.toString(arraySlice));
}
}

Code Explanation

  • Initialize a string array containing the given elements and log it on the console.
  • Specify the first and last index from the original array for slicing the array accordingly.
  • Now, create a new string array “arraySlice” having a size equal to the specified last index value.
  • Apply the “System.arraycopy()” method that copies the original array elements from the start index and then adds to the “arraySlice” array.
  • This copying is done according to the “arraySlice” array’s length i.e., 2.
  • Lastly, display the array as a string.

Output

Approach 5: Slice an Array in Java Using “Stream API”

The “Stream API” processes the object collection and helps in sorting, and filtering the elements. This API is used here to slice an array by creating a stream that skips and limits the elements:

package jbArticles;
import java.util.Arrays;
public class Slicearray {
public static void main(String args[]) {
  int[] givenArray = {1, 2, 3, 4, 5};
  System.out.println("Given Array -> "+Arrays.toString(givenArray));
  int firstIndex = 1, lastIndex = 3;
  int[] arraySlice = Arrays.stream(givenArray).skip(firstIndex).limit(lastIndex).toArray();
  System.out.println("Sliced Array -> "+Arrays.toString(arraySlice));
}
}

Code Explanation

Recall the steps for initializing an array, returning it as a string, and specifying the first and last indexes. Now, use the “Stream API” that takes the original array, skips its first element, and returns the remaining elements till the last index(inclusive) as a new array.

Output

How to Resize an Array in Java?

An array can also be resized to a smaller or a larger size based on requirements using different methods. The below code uses the “Arrays.copyOf()” method which is the most convenient for resizing an array.

This method basically declares a new array with the same elements as that of the original array.

Syntax

public static int[] copyOf(int[] arr, int len)

Syntax Explanation

  • arr” represents the array to be resized/copied.
  • len” is the length of the array(new).

The below code resizes an array to a smaller size:

package jbArticles;
import java.util.Arrays;
public class Slicearray {
public static void main(String[] args) {
  int[] givenArray = {1, 2, 3, 4, 5};
  System.out.println("Original Array -> "+Arrays.toString(givenArray));
  int resize = 2;
  int[] resizedArray = Arrays.copyOf(givenArray, resize);
  givenArray = null;
  System.out.println("Resized Array -> "+Arrays.toString(resizedArray));
}
}

Code Explanation

  • Define an integer array and log it as a string on the console.
  • Initialize the size value of the new array to resize the default array accordingly.
  • Use the “Arrays.copyOf()” method to copy only the first two elements from the default array.
  • Assign the original array as “null” to save the memory used by this array.
  • Display the resized array as a string. 

Output

However, to resize an array to a larger size, specify the size accordingly:

Conclusion

An array in Java can be sliced by copying elements to a new array, the “Arrays.copyOfRange()” method, “Java 8 Stream”, the “arrayCopy()” method, or using “Stream API”. 

Since there is no direct method to slice an array, this slicing is done with the help of an additional array. 

The elements are added to this array using the “for” loop or copying the elements from the original array which varies from method to method.