Copy values from one object to another java


 * This program is used to copy the values one object into another object using constructor.
 * @author W3spoint
public class CopyValuesConstructor {
       int id;
       String name;               
       CopyValuesConstructor(int id, String name){
            System.out.println("Constructor called.");
   = id;
   = name;
        //Copy value of one object into another.
        CopyValuesConstructor(CopyValuesConstructor obj){
            System.out.println("Constructor called for copying value.");
        public static void main(String args[]){
           //parameterized constructor call
           CopyValuesConstructor obj1 = new CopyValuesConstructor(10, "W3spoint");
           //print values of object properties.  
           System.out.println("obj1 id = " +;
           System.out.println("obj1 name = " +;
           //Constructor call to copy the value of one object into other.
           CopyValuesConstructor obj2 = new CopyValuesConstructor(obj1);
           //print values of object properties. 
           System.out.println("obj2 id = " +;
           System.out.println("obj2 name= " +;


Constructor called. 
obj1 id = 10
obj1 name = W3spoint  
Constructor called for copying value.    
obj2 id = 10  
obj2 name= W3spoint

Java interview questions on constructor

Content Protection by