🌐
Oracle
docs.oracle.com › javase › tutorial › essential › io › copy.html
Copying a File or Directory (The Java™ Tutorials > Essential Java Classes > Basic I/O)
import static java.nio.file.StandardCopyOption.*; ... Files.copy(source, target, REPLACE_EXISTING); In addition to file copy, the Files class also defines methods that may be used to copy between a file and a stream. The copy(InputStream, Path, CopyOptions...) method may be used to copy all ...
🌐
Oracle
docs.oracle.com › javase › tutorial › essential › io › examples › Copy.java
Java Copy example
CopyOption[] options = (preserve) ? new CopyOption[] { COPY_ATTRIBUTES } : new CopyOption[0]; Path newdir = target.resolve(source.relativize(dir)); try { Files.copy(dir, newdir, options); } catch (FileAlreadyExistsException x) { // ignore } catch (IOException x) { System.err.format("Unable to create: %s: %s%n", newdir, x); return SKIP_SUBTREE; } return CONTINUE; } @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) { copyFile(file, target.resolve(source.relativize(file)), prompt, preserve); return CONTINUE; } @Override public FileVisitResult postVisitDirectory(Path
Discussions

Java copy method
https://docs.oracle.com/javase/8/docs/api/java/lang/Cloneable.html Although this doesn't allow you to change the values per-say. If your object is mutable however, you can just change the properties on the cloned object afterwards. If your object is immutable, you will need to create your own method that can return a "changed" object. More on reddit.com
🌐 r/javahelp
12
9
October 28, 2021
How do I copy an object in Java? - Stack Overflow
Below image shows obj1 after a deep copy has been performed on it. Not only has obj1 been copied, but the objects contained within it have been copied as well. We can use Java Object Serialization to make a deep copy. Unfortunately, this approach has some problems too(detailed examples). More on stackoverflow.com
🌐 stackoverflow.com
Record copy()/with() is being worked on
record Person(String name) implements CopyableRecord<Person> {} 
var guruJava = new Person("Brian Goetz"); 
var guruCSharp = guruJava.with(Person::name, "Eric Lippert");

record Person(String firstName, String lastName, int age) implements CopyableRecord<Person> {} 
new Person("James", "Gosling", 0).with(Person::age, 65));
// Person[firstName=James, lastName=Gosling, age=65]}

Yeah, thats actually possible, even right now. Relevant Gist, my blog post about it.

I really hope they take the time to enhance method references a bit so that this works better instead of the alternatives. LINQ in C# already does a lot of inspection of the provided lambdas, there is no reason Java can't do the same.

More on reddit.com
🌐 r/java
19
84
July 27, 2020
[Java]Is there a way to copy an object without copy constructor?
If the object has getters/setters you could do something like this public class MyObjectCopier { public static MyObject copy(MyObject toCopy) { MyObject obj = new MyObject(); obj.setPropertyA(toCopy.getPropertyA()); obj.setPropertyB(toCopy.getPropertyB()); return obj; } } More on reddit.com
🌐 r/learnprogramming
4
4
November 23, 2015
🌐
GeeksforGeeks
geeksforgeeks.org › java › collections-copy-method-in-java-with-examples
Collections copy() method in Java with Examples - GeeksforGeeks
May 15, 2019 - Value of source list: [Ram, Gopal, Verma] Value of destination list: [1, 2, 3] After copying: Value of source list: [Ram, Gopal, Verma] Value of destination list: [Ram, Gopal, Verma] Example 2: For IndexOutOfBoundsException ... // Java program to demonstrate // copy() method import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { // creating object of Source list and destination List List<String> srclst = new ArrayList<String>(3); List<String> destlst = new ArrayList<String>(2); // Adding element to srclst srclst.add("Ram"); srclst.add("Gopal");
🌐
EDUCBA
educba.com › home › software development › software development tutorials › java tutorial › copy() in java
copy() in Java | How copy() method works in Java | Examples
April 1, 2023 - In the case of the above program, 2 lists are taken and sent to the copy() method as arguments, but since the size of the destination list is smaller than the size of the source list, thus, IndexOutOfBoundsException occurs. Such an issue is solved in the below example, where the size of the destination list is the same as the source list. ... import java.util.*; public class Demo { public static void main(String[] args) { List<String> mysrclist = new ArrayList<String>(6); List<String> mydestlist = new ArrayList<String>(11); mysrclist.add("Lets practice"); mysrclist.add("Java"); mysrclist.add("
Address   Unit no. 202, Jay Antariksh Bldg, Makwana Road, Marol, Andheri (East),, 400059, Mumbai
🌐
Baeldung
baeldung.com › home › java › java io › how to copy a file with java
How to Copy a File with Java | Baeldung
January 4, 2024 - The NIO.2 Files class provides a set of overloaded copy() methods for copying files and directories within the file system. Let’s take a look at an example using copy() with two Path arguments:
🌐
DigitalOcean
digitalocean.com › community › tutorials › java-copy-file
Java Copy File - 4 Ways to Copy File in Java | DigitalOcean
August 3, 2022 - This is the conventional way of file copy in java. Here we create two Files - source and destination. Then we create InputStream from source and write it to the destination file using OutputStream for java copy file operation.
🌐
GeeksforGeeks
geeksforgeeks.org › java › deep-shallow-lazy-copy-java-examples
Deep, Shallow and Lazy Copy with Java Examples - GeeksforGeeks
January 23, 2026 - ... import java.util.Arrays; class Ex { private int[] data; // Shallow copy public Ex(int[] values) { this.data = values; } public void showData() { System.out.println(Arrays.toString(data)); } }
🌐
GeeksforGeeks
geeksforgeeks.org › java › files-copy-method-in-java-with-examples
Files copy() Method in Java with Examples - GeeksforGeeks
July 20, 2022 - UnsupportedOperationException: If the way of copying described by an option is not supported · SecurityException: If the write access to the target file is denied by the security manager ... // Importing classes from java.nio package as // this package is responsible for network linking import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; // Main Class public class GFG { // Main driver method public static void main(String[] args) { // Path of file where data is to copied Path pathIn = (Path)Pat
Find elsewhere
🌐
GeeksforGeeks
geeksforgeeks.org › java › array-copy-in-java
Array Copy in Java - GeeksforGeeks
July 23, 2025 - This program shows that cloning a multi-dimensional array creates a shallow copy—the top-level array is duplicated, but inner arrays are still shared references. We can also use System.arraycopy() Method. The system is present in java.lang package.
🌐
Baeldung
baeldung.com › home › java › core java › how to make a deep copy of an object in java
How to Make a Deep Copy of an Object in Java | Baeldung
March 26, 2025 - Learn several different ways how to copy a Set in Java. ... We’ll use three Maven dependencies, Gson, Jackson, and Apache Commons Lang, to test different ways of performing a deep copy.
🌐
Medium
medium.com › @AlexanderObregon › javas-files-copy-method-explained-aba9aeb73486
Java’s Files.copy() Method Explained | Medium
January 12, 2025 - For scenarios requiring high performance or customization, using FileChannel can provide better control over the copy process. The transferTo or transferFrom methods in FileChannel allow direct transfer of data between file channels, often resulting in faster operations. ... import java.io.*; import java.nio.channels.FileChannel; public class LargeFileCopy { public static void main(String[] args) { File sourceFile = new File("largeFile.dat"); File targetFile = new File("largeFile_copy.dat"); try (FileChannel sourceChannel = new FileInputStream(sourceFile).getChannel(); FileChannel targetChanne
🌐
Reddit
reddit.com › r/javahelp › java copy method
r/javahelp on Reddit: Java copy method
October 28, 2021 -

Hello there! I need some kind an advice. I'm trying to find out some library for Java providing possibility to copy object with changed values. For example, in Scala we have method copy() in case classes copying all fields to another one. Also there is an approach to define which fields will be changed by passing them into copy(). Does something like this exist in Java world?

Top answer
1 of 16
713

Create a copy constructor:

class DummyBean {
  private String dummy;

  public DummyBean(DummyBean another) {
    this.dummy = another.dummy; // you can access  
  }
}

Every object has also a clone method which can be used to copy the object, but don't use it. It's way too easy to create a class and do improper clone method. If you are going to do that, read at least what Joshua Bloch has to say about it in Effective Java.

2 of 16
460

Basic: Object Copying in Java.

Let us Assume an object- obj1, that contains two objects, containedObj1 and containedObj2.

shallow copying:
shallow copying creates a new instance of the same class and copies all the fields to the new instance and returns it. Object class provides a clone method and provides support for the shallow copying.

Deep copying:
A deep copy occurs when an object is copied along with the objects to which it refers. Below image shows obj1 after a deep copy has been performed on it. Not only has obj1 been copied, but the objects contained within it have been copied as well. We can use Java Object Serialization to make a deep copy. Unfortunately, this approach has some problems too(detailed examples).

Possible Problems:
clone is tricky to implement correctly.
It's better to use Defensive copying, copy constructors(as @egaga reply) or static factory methods.

  1. If you have an object, that you know has a public clone() method, but you don’t know the type of the object at compile time, then you have problem. Java has an interface called Cloneable. In practice, we should implement this interface if we want to make an object Cloneable. Object.clone is protected, so we must override it with a public method in order for it to be accessible.
  2. Another problem arises when we try deep copying of a complex object. Assume that the clone() method of all member object variables also does deep copy, this is too risky of an assumption. You must control the code in all classes.

For example org.apache.commons.lang.SerializationUtils will have method for Deep clone using serialization(Source). If we need to clone Bean then there are couple of utility methods in org.apache.commons.beanutils (Source).

  • cloneBean will Clone a bean based on the available property getters and setters, even if the bean class itself does not implement Cloneable.
  • copyProperties will Copy property values from the origin bean to the destination bean for all cases where the property names are the same.
🌐
InfoWorld
infoworld.com › home › blogs › java challengers
Shallow and deep copy: Two ways to copy objects in Java | InfoWorld
January 4, 2024 - See my InfoWorld article, Does Java pass by reference or pass by value? for a deeper exploration of object references. The shallow copy technique allows us to copy simple object values to a new object without including the internal object values. As an example, here’s how to use the shallow copy technique to copy the Product object without using its object reference:
🌐
CodeGym
codegym.cc › java blog › java arrays › arrays.copyof() method in java
Arrays.copyOf() Method in Java
December 24, 2024 - Copying 2D arrays manually using loops ensures greater control and enables deep copying, which creates new instances of nested arrays. import java.util.Arrays; public class ManualCopyExample { public static void main(String[] args) { int[][] original = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; int[][] copy = new int[original.length][]; for (int i = 0; i < original.length; i++) { copy[i] = Arrays.copyOf(original[i], original[i].length); } System.out.println("Original: " + Arrays.deepToString(original)); System.out.println("Copy: " + Arrays.deepToString(copy)); } }
🌐
ZetCode
zetcode.com › java › copyfile
Java copy file - learn how to copy a file in Java
import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; void main() throws IOException { var source = new File("bugs.txt"); var dest = new File("bugs2.txt"); try (var fis = new FileInputStream(source); var fos = new FileOutputStream(dest)) { byte[] buffer = new byte[1024]; int length; while ((length = fis.read(buffer)) > 0) { fos.write(buffer, 0, length); } } } The example copies a file using FileInputStream, FileOutputStream, and File.
🌐
Programiz
programiz.com › java-programming › copy-arrays
Java Copy Arrays (Using System arraycopy(), Looping construct and so on)
... class Main { public static ... System.out.print(number + ", "); } } } ... In the above example, we have used the assignment operator (=) to copy an array named numbers to another array named positiveNumbers....
🌐
Medium
medium.com › @pratik.941 › understanding-the-cloneable-interface-shallow-copy-and-deep-copy-in-java-73c45066ecb1
Understanding the Cloneable Interface, Shallow Copy, and Deep Copy in Java | by Pratik T | Medium
October 1, 2024 - When working with objects in Java, it’s often necessary to create copies of objects. However, simply copying the reference of an object can…
🌐
Medium
medium.com › @alxkm › how-to-deep-copy-an-object-in-java-approaches-best-practices-e9de941e7f1f
Java Interview: How to Deep Copy an Object in Java-Approaches & Best Practices | by Alex Klimenko | Medium
August 9, 2025 - Deep copy creates entirely new objects recursively-including all nested fields. Let's take an example: class Address { String city; } class Person { String name; Address address; } If you shallow-copy Person, the Address object is still shared.
🌐
DataCamp
datacamp.com › doc › java › copyof
Java Array copyOf()
import java.util.Arrays; public ... Array: " + Arrays.toString(truncatedArray)); } } In this example, Arrays.copyOf() creates a new array truncatedArray with only the first two elements of originalArray....