Introduction
Merging two string arrays is a common task in programming, especially when dealing with collections of data. This exercise helps you understand how to work with arrays and concatenate their elements into a single array in Java. This guide will walk you through writing a Java program that merges two string arrays into one.
Problem Statement
Create a Java program that:
- Defines two string arrays.
- Merges these two arrays into a single array.
- Displays the merged array.
Example:
- Input Arrays:
String[] array1 = {"Apple", "Banana", "Cherry"}; String[] array2 = {"Date", "Fig", "Grape"}; - Output:
Merged array: ["Apple", "Banana", "Cherry", "Date", "Fig", "Grape"]
Solution Steps
- Define Two String Arrays: Create two string arrays with predefined values.
- Create a Merged Array: Initialize a new array that will hold the elements of both arrays.
- Copy Elements to Merged Array: Use the
System.arraycopy()method to copy elements from both arrays into the merged array. - Display the Merged Array: Print the merged array.
Java Program
// Java Program to Merge Two String Arrays
// Author: https://www.rameshfadatare.com/
import java.util.Arrays;
public class StringArrayMerger {
public static void main(String[] args) {
// Step 1: Define two string arrays
String[] array1 = {"Apple", "Banana", "Cherry"};
String[] array2 = {"Date", "Fig", "Grape"};
// Step 2: Create a merged array
String[] mergedArray = new String[array1.length + array2.length];
// Step 3: Copy elements from both arrays to the merged array
System.arraycopy(array1, 0, mergedArray, 0, array1.length);
System.arraycopy(array2, 0, mergedArray, array1.length, array2.length);
// Step 4: Display the merged array
System.out.println("Merged array: " + Arrays.toString(mergedArray));
}
}
Explanation
Step 1: Define Two String Arrays
- Two string arrays,
array1andarray2, are initialized with predefined values.
Step 2: Create a Merged Array
- A new string array,
mergedArray, is created with a size equal to the sum of the lengths ofarray1andarray2.
Step 3: Copy Elements to the Merged Array
- The
System.arraycopy()method is used to copy the elements fromarray1to the beginning ofmergedArray. - The same method is then used to copy the elements from
array2to the end ofmergedArray, starting from the index after the last element ofarray1.
Step 4: Display the Merged Array
- The
Arrays.toString()method is used to convert the merged array to a string for easy printing.
Output Example
Example:
Merged array: [Apple, Banana, Cherry, Date, Fig, Grape]
Conclusion
This Java program demonstrates how to merge two string arrays into a single array. It covers essential concepts such as array manipulation, using the System.arraycopy() method, and printing arrays, making it a useful exercise for beginners learning Java programming.