Java Program to Split an Array from Specified Position
Last Updated :
26 Nov, 2024
In Java, splitting an array means dividing the array into two parts based on a given position. This operation creates two new arrays that represent the segments before and after the given index.
Example:
The simplest way to split an array in Java from a specified position is by using the in-built Arrays.copyOfRange() method.
Java
// Java Program to Split Array
// Using Arrays.copyOfRange()
import java.util.Arrays;
public class SplittingArray {
public static void main(String args[]) {
// Original Array
int a[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
int n = a.length;
// Position to split the array
int p = 5;
// Validate the split position to ensure
// it's within array bounds
if (p > 0 && p < n) {
int b[] = new int[p];
int c[] = new int[n - p];
// Initialize array "b" with elements from index 0 to p - 1
b = Arrays.copyOfRange(a, 0, p);
// Initialize array "c" with elements from index p to n - 1
c = Arrays.copyOfRange(a, p, n);
System.out.println(Arrays.toString(b));
System.out.println(Arrays.toString(c));
}
else {
System.out.println("Invalid position.");
}
}
}
Output[1, 2, 3, 4, 5]
[6, 7, 8, 9, 0]
Other Ways to Split an Array from Specified Position
Using a Single for loop
This method is more efficient solution because it only requires one pass over the array. When we want to split an array at a specified position with minimal complexity, this approach is optimal, compared to using multiple loops or in-built methods.
Java
// Java Program to Split Array
// using only one for loop
import java.util.Arrays;
public class SplittingArray2 {
public static void main(String args[]) {
// original array
int a[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
int n = a.length;
int p = 5;
if (p > 0 && p < n) {
int b[] = new int[p];
int c[] = new int[n - p];
// only using one for loop to split the array into b and c
for (int i = 0; i < n; i++) {
if (i < p) {
b[i] = a[i];
} else {
c[i - p] = a[i];
}
}
System.out.println(Arrays.toString(b));
System.out.println(Arrays.toString(c));
}
else {
System.out.println("Invalid position.");
}
}
}
Output[1, 2, 3, 4, 5]
[6, 7, 8, 9, 0]
Explanation: First, we declare two arrays "b"
and "c"
with sizes "p"
and "n - p"
, respectively. Then, we use a single loop to fill both arrays based on the index position.
Using Two for
Loops
This method uses separate loops to fill each new array. This is less efficient than a single-loop approach. It can be useful when readability is prioritized over performance specially for smaller arrays.
Java
// Java Program to Split Array
// Using two for loops
import java.util.Arrays;
public class SplittingArray3 {
public static void main(String args[]) {
// Original array
int a[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
int n = a.length;
int p = 5;
// validating the position for invalid values
if (p > 0 && p < n) {
// declaring array b and c
int b[] = new int[p];
int c[] = new int[n - p];
for (int i = 0; i < p; i++) {
b[i] = a[i];
}
for (int i = 0; i < n - p; i++) {
c[i] = a[i + p];
}
System.out.println(Arrays.toString(b));
System.out.println(Arrays.toString(c));
}
else {
System.out.println("Invalid position.");
}
}
}
Output[1, 2, 3, 4, 5]
[6, 7, 8, 9, 0]
Explanation: First, we declare two arrays b
and c
with sizes p
and n - p
, respectively. Then we use two loops, the first loop runs from 0 to p, initializing array b. The second loop runs from 0 to n - p ,initializing array c.
Similar Reads
Java Tutorial Java is a high-level, object-oriented programming language used to build web apps, mobile applications, and enterprise software systems. It is known for its Write Once, Run Anywhere capability, which means code written in Java can run on any device that supports the Java Virtual Machine (JVM).Java s
10 min read
Java Interview Questions and Answers Java is one of the most popular programming languages in the world, known for its versatility, portability, and wide range of applications. Java is the most used language in top companies such as Uber, Airbnb, Google, Netflix, Instagram, Spotify, Amazon, and many more because of its features and per
15+ min read
Java OOP(Object Oriented Programming) Concepts Java Object-Oriented Programming (OOPs) is a fundamental concept in Java that every developer must understand. It allows developers to structure code using classes and objects, making it more modular, reusable, and scalable.The core idea of OOPs is to bind data and the functions that operate on it,
13 min read
Arrays in Java Arrays in Java are one of the most fundamental data structures that allow us to store multiple values of the same type in a single variable. They are useful for storing and managing collections of data. Arrays in Java are objects, which makes them work differently from arrays in C/C++ in terms of me
15+ min read
Inheritance in Java Java Inheritance is a fundamental concept in OOP(Object-Oriented Programming). It is the mechanism in Java by which one class is allowed to inherit the features(fields and methods) of another class. In Java, Inheritance means creating new classes based on existing ones. A class that inherits from an
13 min read
Collections in Java Any group of individual objects that are represented as a single unit is known as a Java Collection of Objects. In Java, a separate framework named the "Collection Framework" has been defined in JDK 1.2 which holds all the Java Collection Classes and Interface in it. In Java, the Collection interfac
15+ min read
Java Exception Handling Exception handling in Java allows developers to manage runtime errors effectively by using mechanisms like try-catch block, finally block, throwing Exceptions, Custom Exception handling, etc. An Exception is an unwanted or unexpected event that occurs during the execution of a program, i.e., at runt
10 min read
Java Programs - Java Programming Examples In this article, we will learn and prepare for Interviews using Java Programming Examples. From basic Java programs like the Fibonacci series, Prime numbers, Factorial numbers, and Palindrome numbers to advanced Java programs.Java is one of the most popular programming languages today because of its
8 min read
Java Interface An Interface in Java programming language is defined as an abstract type used to specify the behaviour of a class. An interface in Java is a blueprint of a behaviour. A Java interface contains static constants and abstract methods. Key Properties of Interface:The interface in Java is a mechanism to
12 min read
Polymorphism in Java Polymorphism in Java is one of the core concepts in object-oriented programming (OOP) that allows objects to behave differently based on their specific class type. The word polymorphism means having many forms, and it comes from the Greek words poly (many) and morph (forms), this means one entity ca
7 min read