Java Utility Library

Java Object - clone() Method



The java.util.Object.clone() method is used to create and return a copy of this object. The precise meaning of "copy" may depend on the class of the object. The general intent is that, for any object x, the expression:

x.clone() != x

will be true, and that the expression:

x.clone().getClass() == x.getClass()

will be true, but these are not absolute requirements. While it is typically the case that:

x.clone().equals(x)

will be true, this is not an absolute requirement.

Syntax

protected Object clone()
                throws CloneNotSupportedException

Parameters

No parameter is required.

Return Value

Returns a clone of this instance.

Exception

Throws CloneNotSupportedException, if the object's class does not support the Cloneable interface. Subclasses that override the clone method can also throw this exception to indicate that an instance cannot be cloned.

Example:

In the example below, the java.util.Object.clone() method returns a clone of the given object.

import java.lang.*;

public class MyClass {
  public static void main(String[] args) {
    //creating Object
    int obj1[] = {10, 5, 25, -10, -30};

    //printing the obj1 content
    System.out.print("obj1 contains:"); 
    for(int i: obj1)
      System.out.print(" " + i);

    //creating a clone of obj1 into obj2
    int obj2[] = obj1.clone();

    //printing the obj2 content
    System.out.print("\nobj2 contains:"); 
    for(int j: obj2)
      System.out.print(" " + j);
  }
}

The output of the above code will be:

obj1 contains: 10 5 25 -10 -30
obj2 contains: 10 5 25 -10 -30

❮ Java.lang - Object