Tech
News
Videos
Forums
Jobs
Books
Events
More
Interviews
Live
Learn
Training
Career
Members
Blogs
Challenges
Certification
Contribute
Article
Blog
Video
Ebook
Interview Question
Collapse
Feed
Dashboard
Wallet
Learn
Achievements
Network
Rewards
SharpGPT
Premium
Contribute
Article
Blog
Video
Ebook
Interview Question
Register
Login
Wanna Copy An Array in Java
WhatsApp
Gagan Bansal
5y
12.2
k
0
0
25
Blog
Hi Friends
To copy an array in JAVA we have 3 options.
Manually iterating elements of the source array and placing each one into the destination array using a loop.
arraycopy() Method of java.lang.System class
Method syntax
public
static
void
arraycopy(Object src,
int
srcPos, Object dest,
int
destPos,
int
length)
Demo Program
class
ArrayCopyDemo {
public
static
void
main(String[] args) {
char
[] copyFrom = {
'd'
,
'e'
,
'c'
,
'a'
,
'f'
,
'f'
,
'e'
,
'i'
,
'n'
,
'a'
,
't'
,
'e'
,
'd'
};
char
[] copyTo =
new
char
[
7
];
System.arraycopy(copyFrom,
2
, copyTo,
0
,
7
);
System.out.println(
new
String(copyTo));
}
}
The
output
from this program is:
caffein
copyOfRange() Method of java.util.Arrays class
Demo Program
class
ArrayCopyOfDemo {
public
static
void
main(String[] args) {
char
[] copyFrom = {
'd'
,
'e'
,
'c'
,
'a'
,
'f'
,
'f'
,
'e'
,
'i'
,
'n'
,
'a'
,
't'
,
'e'
,
'd'
};
char
[] copyTo = java.util.Arrays.copyOfRange(copyFrom,
2
,
9
);
System.out.println(
new
String(copyTo));
}
}
The
output
from this program is:
caffein
The difference between the 2nd and 3rd is that using the copyOfRange method does not require you to create the destination array before calling the method because the destination array is returned by the method. Although it requires fewer lines of code.
Refer java docs by Oracle
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html
Wanna Copy An Array in Java
Up Next
Copy one file to another in java
Ebook Download
View all
Programming in Java
Read by 640 people
Download Now!
Learn
View all
Membership not found