Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,845 questions

51,766 answers

573 users

How to remove a subarray from an array in Java

2 Answers

0 votes
import java.util.Arrays;

public class Main {
    public static int[] removeSubarray(int[] array, int start, int end) {
        int[] firstPart = Arrays.copyOfRange(array, 0, start);
        int[] secondPart = Arrays.copyOfRange(array, end + 1, array.length);

        // Combine the two parts
        int[] result = new int[firstPart.length + secondPart.length];
        System.arraycopy(firstPart, 0, result, 0, firstPart.length);
        System.arraycopy(secondPart, 0, result, firstPart.length, secondPart.length);

        return result;
    }
    public static void main(String[] args) {
        int[] array = {1, 2, 3, 4, 5, 6, 7, 8};
        int start = 2, end = 4;

        int[] result = removeSubarray(array, start, end);
        System.out.println(Arrays.toString(result)); 
    }
}

 
 
/*
run:
 
[1, 2, 6, 7, 8]
 
*/

 



answered Aug 14, 2025 by avibootz
0 votes
import java.util.Arrays;

public class Main {
    public static int[] removeSubarray(int[] array, int start, int end) {
        int newLength = array.length - (end - start + 1);
        int[] result = new int[newLength];
    
        // Copy elements before the start index
        System.arraycopy(array, 0, result, 0, start);
    
        // Copy elements after the end index
        System.arraycopy(array, end + 1, result, start, array.length - end - 1);
    
        return result;
    }
    public static void main(String[] args) {
        int[] array = {1, 2, 3, 4, 5, 6, 7, 8};
        int start = 2, end = 4;

        int[] result = removeSubarray(array, start, end);
        System.out.println(Arrays.toString(result)); 
    }
}

 
 
/*
run:
 
[1, 2, 6, 7, 8]
 
*/

 



answered Aug 14, 2025 by avibootz
...