Object creation

We java folks have ever wondered how many ways can we create objects in Java and what are the benefits and pitfalls of each method ? In this short blog, I am going to discuss the pros and cons of some of the most popular ways of object creation in Java. Please refer to my Github project ObjectCreationAndCloning for this.

So let us see the most popular ways of object creation in Java:

It clearly indicates that new operator is costliest while cloning operation is fastest and the reflection is actually faster than new operator!

Deep copy in Serialization

Another interesting aspect of Java cloning is that by default - the clone() method does shallow copy only whioch means the object references are not replicated but instead - both the original and cloned objects internal object references pointt to the same reference. So in order to overcome this, there are various ways in which we can properly clone nested objects also, this approiach is known as deep copy. Below are some ways in which the same can be achieved: