In Java, copying the elements of one array to another is a common operation that can be accomplished in several ways. This article will demonstrate how to copy all elements from one array to another using the Scanner class for user input. We will cover a simple iterative method to achieve this.
Understanding Arrays in Java
An array in Java is a data structure that holds a fixed number of values of a single type. When you need to duplicate an array, it's essential to create a new array and copy the elements to avoid reference issues. Simply assigning one array to another will only create a reference to the original array, meaning changes to one will affect the other.
Copying an Array using user input
Here’s a complete Java program that demonstrates how to copy all elements from one array to another using user input.
Code example
import java.util.Scanner;
public class ArrayCopyExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Input: Size of the array
System.out.print("Enter the size of the array: ");
int size = scanner.nextInt();
// Initialize the source array
int[] sourceArray = new int[size];
// Input: Elements of the source array
System.out.println("Enter " + size + " elements:");
for (int i = 0; i < size; i++) {
sourceArray[i] = scanner.nextInt();
}
// Initialize the destination array
int[] destinationArray = new int[size];
// Copying elements from sourceArray to destinationArray
for (int i = 0; i < size; i++) {
destinationArray[i] = sourceArray[i];
}
// Output: Displaying the copied array
System.out.println("Copied Array:");
for (int element : destinationArray) {
System.out.print(element + " ");
}
// Close the scanner
scanner.close();
}
}
Explanation
- Importing Scanner: We import java.util.Scanner to read user input.
- User Input for Array Size: The program prompts the user to enter the size of the array.
- Initializing Source Array: We create an integer array named sourceArray based on the specified size.
- Inputting Elements: A loop allows users to enter elements into sourceArray.
- Initializing Destination Array: We declare another integer array named destinationArray of the same size.
- Copying Elements: A loop iterates through sourceArray, copying each element into destinationArray.
- Displaying Copied Array: Finally, we print out the elements of destinationArray.
- Closing Scanner: The scanner is closed to prevent resource leaks.
Run the Program
To run this program
- Save it as ArrayCopyExample.java.
- Open your terminal or command prompt.
- Navigate to the directory where you saved the file.
- Compile the program
javac ArrayCopyExample.java
-
Run the compiled class.
java ArrayCopyExample
Output
Copy array in Java Using System.arraycopy()
Copying All Elements of One Array to Another Array in Java Using System.arraycopy().
Code example
Here’s a simple example demonstrating how to copy all elements from one array to another using System.arraycopy():
public class ArrayCopyExample {
public static void main(String[] args) {
// Source array
int[] sourceArray = {1, 2, 3, 4, 5};
// Destination array with the same length as source
int[] destinationArray = new int[sourceArray.length];
// Copy all elements from sourceArray to destinationArray
System.arraycopy(sourceArray, 0, destinationArray, 0, sourceArray.length);
// Displaying the contents of the destination array
System.out.println("Elements in the destination array:");
for (int element : destinationArray) {
System.out.print(element + " ");
}
}
}
Explanation
- Source Array: We define an integer array named sourceArray with some values.
- Destination Array: We create a new integer array called destinationArray that is the same length as sourceArray.
- Copying Elements: We call System.arraycopy() to copy all elements from sourceArray starting at index 0 to destinationArray starting at index 0 for a total length equal to the length of sourceArray.
- Displaying Results: Finally, we print the contents of destinationArray.
Output
Copying a Subset of Elements of Array in Java
You can also copy a specific range of elements from one array to another. Here’s an example that demonstrates this:
Code example
public class ArrayCopySubsetExample {
public static void main(String[] args) {
// Source array
char[] sourceArray = {'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd'};
// Destination array with sufficient size
char[] destinationArray = new char[5];
// Copying a subset of elements (from index 6 to 10)
System.arraycopy(sourceArray, 6, destinationArray, 0, 5);
// Displaying the contents of the destination array
System.out.println("Copied subset in the destination array:");
System.out.println(new String(destinationArray)); // Convert char array to String
}
}
Explanation
- Source Array: A character array named sourceArray is defined.
- Destination Array: A smaller character array named destinationArray is created.
- Copying Subset: The method copies characters starting from index 6 of sourceArray into destinationArray, beginning at index 0 for a total length of 5.
- Displaying Results: The contents are printed after converting the character array back to a string.
Output
Conclusion
Copying elements from one array to another in Java is a fundamental operation that can be implemented in various ways depending on the requirements. This article demonstrated manual copying using user input, leveraging the Scanner class and the efficient System.arraycopy() method for seamless copying of arrays. Whether duplicating entire arrays or specific subsets, Java provides robust tools to handle these tasks effectively, ensuring flexibility and ease for developers.