TECHNOLOGIES
FORUMS
JOBS
BOOKS
EVENTS
INTERVIEWS
Live
MORE
LEARN
Training
CAREER
MEMBERS
VIDEOS
NEWS
BLOGS
Sign Up
Login
No unread comment.
View All Comments
No unread message.
View All Messages
No unread notification.
View All Notifications
C# Corner
Post
An Article
A Blog
A News
A Video
An EBook
An Interview Question
Ask Question
Wanna Copy An Array in Java
Gagan Bansal
Sep 28, 2019
12.1
k
0
0
facebook
twitter
linkedIn
Reddit
WhatsApp
Email
Bookmark
In this blog we will learn how to copy Array
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
Next Recommended Reading
Copy one file to another in java