×

Array Slicing in Java

Array slicing is a method in Java for obtaining a subarray of a specified array. Assume a[] is an array. It contains eight items indexed from a[0] to a[7].a[] = {1, 5, 3, 2, 7, 12, 4, 11}

Now we need to locate a slice of a array index between a[4] and a[7]. Where a[4] represents the startIndex and a[7] represents the endIndex. As a result, we have the below sliced array:a[] = {7, 12, 4, 11}

In this section, we'll look at how to use Java to find a slice of an array. There are three methods for locating a slice of an array:

  • By duplicating elements
  • Using the copyOfRange() Method
  • Using Java 8 Stream

Let's go over each method in depth:

Elements Copying Method:

It is a native technique for obtaining an array slice. In this technique, we first determine the beginning and ending indexes of the provided array. Then we make an empty array (sliced array) of size (endIndex - startIndex). Copies the elements (from startIndex) from the provided array to the sliced array. Finally, output the sliced array. Let's put the aforesaid method into action in a Java programme to get a sliced array of the given array. This is a program. An array of primitive types will be used.

SliceArrayExample:

import java.util.Arrays;   
public class SliceArrExample  
{   
public static int[] getSlice(int[] arr, int a, int b)   
{   
int[] slicedArr= new int[b - a];   
for (int i = 0; i < slicedArr.len; i++)   
{   
slicedArr[i] = array[a + i];   
}   
return slicedArr;   
}   
public static void main(String args[])   
{   
int[] arr= {1, 5, 8, 2, 4, 9, 6, 11, 0, 3};   
int a= 4, b = 7;   
int[] slicedArr= getSlice(arr, a, b + 1);   
System.out.println("Slice of Arr: "+Arrays.toStr(slicedArr));   
}   
}  

Output:

Slice of Arr: [4, 9, 6, 11]

Using the copyOfRange() Function:

The copyOfRange() method is a member of the Java Arrays class. It replicates the array's specified range to the newly formed array (slice array) and provides the newly produced array containing the array's specified range from the original array. The slicing of an array takes O(n) time and O(n) space to contain elements, where n represents the number of elements in the new array.

Syntax:

public static int[] copyOfRange(int[] original, int from, int to)

The method parses the following three parameters:

  • original: It is an array whose slice must be discovered.
  • It is the starting index. It must be in the range of 0 to the length of the provided array.
  • It is the final index.

The following exceptions are thrown:

  • If from is less than 0 or higher than the length of the provided array, an ArrayIndexOutOfBoundsException is thrown.
  • If the parameter from is bigger than the parameter to, an IllegalArgumentException is thrown.
  • If the provided array is null, a NullPointerException is thrown.

SliceArrayExample1:

import java.util.Arrays;   
public class SliceArrExample1 
{   
public static int[] slice(int[] arr, int a, int b)   
{   
int[] slicedArr = Arrays.copyOfRange(arr, a, b);   
return slicedArr;   
}   
public static void main(String args[])   
{   
//getting array, a and b   
int[] arr= {1, 2, 6, 9, 11, 8, 5, 4, 3};   
int a= 1, b = 5;   
int[] sliceArr= slice(arr, a, b+ 1);   
System.out.println("Slice of Arr: "+Arrays.toStr(sliceArr));   
}   
}   

Output:

Slice of Arr: [2, 6, 9,11, 8]

Using the Java 8 Stream:

We may use the Java 8 Stream to find the slicing of an array by following the instructions below.

  • Find the startIndex and endIndex arrays first.
  • Using the range() technique, convert the elements in range into Primitive Stream.
  • Map the requested elements from the supplied array using the map() function.
  • Convert the mapped array to an array by calling the toArray() function.
  • Please print the sliced.

SliceArrayExample2:

import java.util.Arrays;   
import java.util.stream.IntStream;   
public class SliceArrayExample2 
{   
public static int[] findSl(int[] array, int startIndex, int endIndex)   
{   
int[] slcarray = IntStream.range(a, e).map(i -> array[i]).toArr();   
return slcarray;   
}   
//main() method  
public static void main(String args[])   
{   
//Get the array, a and b
int[] array = {2, 5, 9, 5, 4, 10, 3, 8, 7, 12, 0, 9};   
int a= 4, b = 8;   
int[] slcarr = findS(array, a, b + 1);   
//Printing  the slice of the array   
System.out.println("Array for the specified range is: "+Arrays.toStr(slcarr));   
}   
}  

Output:

 Array for the specified range is: [4,10, 3, 8, 7]

Related Topics

Constructor Overloading in Java

In Java, constructors can be overloaded just like methods. The idea of having multiple constructors with various parameter sets so that each function Object()  can carry out a particular task...

3 minutes read.

Java Else Keyword

The else statement specifies a section of Java code that will run if an if statement's condition is false.The following conditional statements can be used in Java:To provide a block...

3 minutes read.

Blocking Queue in Java Example

Let's first briefly comprehend queue before moving on to the topic of "Blocking Queue." A queue seems to be an orderly list of items in which elements are added from...

8 minutes read.

Java String join() method

Java String join() method returns a joined String with given delimiter Syntax: public static String join(CharSequence delimeter,charSequence...elements) public static String join(CharSequence delimeter,Iterable<?extens charSequence>elements) Parameters: delimiter: char value to be added with each element elements: char value...

1 minute read.

Java Primitive Data Types

Primitive data types are the simplest data types in a programming language. They’re predefined in the language. The names of the primitive types are quite descriptive of the values that...

2 minutes read.

ArrayList vs Vector in Java

ArrayList Vs. Vector in Java In Java, the two classes ArrayList and Vector both are associated with Java Collections Framework. Both classes implement java.util.List interface. Even so, these classes have noticeable...

4 minutes read.

Java Boolean logicalXor() Method

The logicalXor() method of Java Boolean class returns the result of implementing logical XOR operation on the specified Boolean operands. Syntax: public static boolean logicalXor (boolean a, boolean b) Parameters: The parameters ‘a’ and...

2 minutes read.

Diffie Hellman Algorithm in Java

In this section, you will be acknowledged about Diffie Hellman algorithm clearly step wise along with an example and also an example program. Diffie Hellman Algorithm One of the most significant algorithms...

3 minutes read.

Java Program to generate binary numbers

A binary tree can create binary numbers ranging from 1 to n. Every node in a tree, the right, and left nodes, has two children, as is common knowledge. The...

3 minutes read.

Java program to find frequency of characters in a string

In this article, you will understand the how to find the frequency of characters in strings by using Java programming language. Along with this, you will understand the hashing concept...

3 minutes read.

String Pool in Java

String Pool in Java: String is one of the most important discussed topics in Java. There are a lot of concepts related to the String and one of them is...

5 minutes read.

Java OCR

In this article, you will be acknowledged about what is a tesseract OCR, how it works, what are its used and advantages and disadvantages. Also, you will be able to...

4 minutes read.

Hidden classes in Java

There specifically are some APIs available in the market that generally is harmful to be used in our programs specifically literally, and until JDK 15, there, for all intents and...

4 minutes read.

Java Boolean logicalAnd() Method

The logicalAnd() method of Java Boolean class returns the result of implementing logicalAND operation on the specified Boolean operands. Syntax:public static boolean logicalAnd (boolean a, boolean b) Parameters:The parameters ‘a’ and ‘b’...

2 minutes read.

Java Arrays Fill

We may use the Arrays.fill () function to fill a whole array or a subset of it. Arrays.fill () may fill both 2D and 3D arrays. Syntax: Arrays.fill(boolean[] fillArr, int fromIndex, int toIndex, boolean val )   Parameters: The array to be filled...

4 minutes read.

How to Iterate List in Java?

List is a Collection foundation interface in Java. It enables us to keep the collection of objects in order. The four classes that make up the List interface implementation are...

3 minutes read.

Java Enum vs Class

Enumerations are used in programming languages to represent collections of named constants. For instance, the four suits in a deck of playing cards might represent four integrators named Club, Diamond,...

7 minutes read.

Java Tutorial

What is Java? Java is an object-oriented, robust, secured and platform-independent programming language. With the help of Java Programming, we can develop console, window, web, enterprise and mobile applications. Java language was...

22 minutes read.

Exception Handling in Java

Before looking at how exceptions are handled in java, it is necessary to see what an exception is. What is Exception? Whenever a program is written, errors are encountered. Some of these...

6 minutes read.

How to check the Java version in cmd

To make programs that can run on our systems, we need to install programming language-related software in our systems. Different programming languages require different types of software, aka IDEs (Integrated...

5 minutes read.