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,959 questions

51,901 answers

573 users

How to split an array into two parts in Java

3 Answers

0 votes
import java.util.Arrays;
 
public class MyClass
{
    public static void main(String[] args)
    {
        int[] arr = { 1, 2, 3, 4, 5, 6, 7 };
        int size = arr.length;
 
        int[] a = new int[(size + 1) / 2];
        int[] b = new int[size - a.length];
 
        for (int i = 0; i < size; i++) {
            if (i < a.length) {
                a[i] = arr[i];
            }
            else {
                b[i - a.length] = arr[i];
            }
        }
 
        System.out.println(Arrays.toString(a));
        System.out.println(Arrays.toString(b));
    }
}




/*
run:

[1, 2, 3, 4]
[5, 6, 7]

*/

 



answered Mar 20, 2023 by avibootz
0 votes
import java.util.Arrays;
 
public class MyClass
{
    public static void main(String[] args)
    {
        int[] arr = { 1, 2, 3, 4, 5, 6, 7 };
        int size = arr.length;
 
        int[] a = new int[(size + 1) / 2];
        int[] b = new int[size - a.length];
 
        System.arraycopy(arr, 0, a, 0, a.length);
        System.arraycopy(arr, a.length, b, 0, b.length);
 
        System.out.println(Arrays.toString(a));
        System.out.println(Arrays.toString(b));
    }
}




/*
run:

[1, 2, 3, 4]
[5, 6, 7]

*/

 



answered Mar 20, 2023 by avibootz
0 votes
import java.util.Arrays;
 
public class MyClass
{
    public static void main(String[] args)
    {
        int[] arr = { 1, 2, 3, 4, 5, 6, 7 };
        int size = arr.length;

        int[] a = Arrays.copyOfRange(arr, 0, (size + 1) / 2);
        int[] b = Arrays.copyOfRange(arr, (size + 1) / 2, size);
 
        System.out.println(Arrays.toString(a));
        System.out.println(Arrays.toString(b));
    }
}




/*
run:

[1, 2, 3, 4]
[5, 6, 7]

*/

 



answered Mar 20, 2023 by avibootz

Related questions

1 answer 133 views
1 answer 135 views
1 answer 130 views
1 answer 116 views
...