Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java Java Objects (Retired) Harnessing the Power of Objects Method Signatures

Does Java has Copy Constructor?

Does Java have Copy Constructor, Deep Copy Shallow Copy?

Can you give some explanation on what you mean? I don't understand your question. Deep copy - shallow copy for what?

2 Answers

Harry James
Harry James
14,780 Points

There isn't a copy constructor itself but, you could always do something like this:

private String string1 = "I am a String";
private String string2;

string2 = string1;

which would mean that string2 would then have the same value as string1. The only disadvantage here is that you must explicitly tell Java what the variable is going to be before you try to set the value.

Hope it helps :)

Mark Rae
Mark Rae
4,503 Points

I'll back up to help other viewers understand the question better. Every variable in memory has the address of where it is in memory and the value it currently holds. So normally 2 variables would each have their own address and their own value.

A deep copy is what most people would think of when they say "copy" in regular conversation: a separate item that has the same properties as the original. A shallow copy is different because instead of being a duplicate of the original, it is an additional reference to the original. The difference is crucial because if someone changes the original, deep copies are unaffected but shallow copies will change because they always reflect the original.

For example, I could copy and paste a quote from another site into this answer, or I could add a link. The quote is a deep copy and the link is a shallow copy. If the other site were to disappear, the quote wouldn't change but the link wouldn't work.

Primitive data types (int, boolean, char, etc.) can be deep copied with the "=" assignment operator. If you use "=" with objects, however, you will create a shallow copy. Deep copies of Java objects are handled several different ways and the best thing to do is to read the object's documentation to find out how that object prefers it.