- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How can we copy one array from another in Java
Let us first create a string array −
String[] arr = new String[] { "P","Q", "R", "S", "T"};
Now, calculate the length of the above array and create a new array with the same length −
int len = arr.length; String[] arr2 = new String[len];
Let us copy one array from another −
System.arraycopy(arr, 0, arr2, 0, arr.length);
Example
public class Demo { public static void main(String[] args) { String[] arr = new String[] { "P","Q", "R", "S", "T"}; System.out.println("Initial array..."); for (int i = 0; i < arr.length; i++) System.out.println(arr[i]); int len = arr.length; String[] arr2 = new String[len]; System.arraycopy(arr, 0, arr2, 0, arr.length); System.out.println("New array...copied"); for (int i = 0; i < arr2.length; i++) System.out.println(arr2[i]); } }
Output
Initial array... P Q R S T New array...copied P Q R S T
Advertisements