Register Now


Lost Password

Enter your email to reset your password.

BY Author

Java – Objects as method parameters

It is also possible to pass an object to a method, exactly same as primitive variables.


public class PassObject 
    int var1;
    int var2;
    public void copy(PassObject obj)
        var1 = obj.var1;
        var2 = obj.var2;

public class PassObjectDemo 
    public static void main(String args[])
        PassObject obj1 = new PassObject();
        PassObject obj2 = new PassObject();
        obj1.var1 = 10;
        obj1.var2 = 20;
        System.out.println("Obj1's var1 = "+obj1.var1);
        System.out.println("Obj1's var2 = "+obj1.var2);
        System.out.println("Obj2's var1 = "+obj2.var1);
        System.out.println("Obj2's var2 = "+obj2.var2);


Obj1's var1 = 10
Obj1's var2 = 20
Obj2's var1 = 10
Obj2's var2 = 20

In the above program, Object obj1 is passed from main() method to copy() method.
In copy() method, variables of obj1 are copied to object obj2 (because the method is invoked by obj2).
Actually passing of object does not mean the whole object is passed but just a reference of the object is passed.

Java Programming Language Object as Method Parameter

Leave a reply