Split Array in Java Example

Split array in java. Splitting an array from a specific location with a Java program. Enter the array’s size, followed by all of the array’s elements. Now type in the location where you want to divide from. The elements from the first position are copied to the second array, and the remaining elements are copied to the third array. the Java source code for Splitting an Array from a Specific Position

import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
int n, x, flag = 1, local = 0, k = 0,j = 0;
Scanner s = new Scanner(System.in);
System.out.print("Enter the number of elements you want in array");
n = s.nextInt();
int a[] = new int[n];
int b[] = new int[n];
int c[] = new int[n];
System.out.println("Enter all the elements");
for (int i = 0; i < n; i++)
{
a[i] = s.nextInt();
}
System.out.print("Enter the position from where you want to split");
local = s.nextInt();
for(int i = 0; i < local; i++)
{
b[k] = a[i];
k++;
}
for(int i = local; i < n; i++)
{
c[j] = a[i];
j++;
}
System.out.print("First array");
for(int i = 0;i < k; i++)
{
System.out.print(b[i]+" ");
}
System.out.println("");
System.out.print("Second array");
for(int i = 0; i < j; i++)
{
System.out.print(c[i]+" ");
}
}
}

 

Output:

Enter the number of elements you want in array 5
Enter all the elements
34
56
678
23
12
Enter the position from where you want to split 678

First array 34 56

Second array 23 12

Array in Java

In Java, an array is a collection of variables that are referred to by a single variable name and an index number. An array’s items are all elements. An array’s elements must all be of the same type. An int array, for example, can contain int values, and a String array can contain strings. Using this program we can split array in java.

For Loop to Execute Split Array in Java

The “for” loop in Java is an entry-controlled loop that allows a user to iteratively execute a block of statement(s) for a fixed number of times. The number of iterations is determined by the test condition specified within the “for” loop. The Java “for” loop is one of the simplest Java loops to grasp. 

A for loop is a repetition control structure that allows you to write a loop that needs to be executed a certain number of times in an efficient manner. When you know how many times a task will be repeated, a for loop comes in handy.

Increment Operator in Java

The increment unary operator in Java increases the value of a variable by one, while the decrement unary operator decreases the value of a variable by one. Both update the operand’s value to its new value. The unary operators increment and decrement have two forms: prefix and postfix.