Register Now

Login

Lost Password

Enter your email to reset your password.

BY Author

Java – Returning Object from method

A method can return any type of object same as another type of data.

Example

class Check 
{
    int var1;
    int var2;
	
    public Check objectReturn()
    {
        Check obj = new Check();
        obj.var1 = 4;
        obj.var2 = 5;
        return obj;
    }
}

class ObjectReturnDemo
{
    public static void main(String args[])
    {
        Check c1 = new Check();
        c1.var1 = 10;
        c1.var2 = 20;
        Check c2 = c1.objectReturn();
        System.out.println("c1's var1 = "+c1.var1);
        System.out.println("c1's var2 = "+c1.var2);
        System.out.println("c2's var1 = "+c2.var1);
        System.out.println("c2's var2 = "+c2.var2);
    }
}

Output

c1's var1 = 10
c1's var2 = 20
c2's var1 = 4
c2's var2 = 5

Now you might be surprised by thinking that how is it possible to get value of Check object obj variables even though objectReturn() method goes out of scope after returning object obj.
It is possible because even though method objectReturn() goes out of scope, Object obj is not destroyed.
Because object obj has reference c2 available to it even though objectReturn() method goes out of scope.
From this we can conclude that object will exist as long as there is a reference available to it.

Java Programming Language return Object from Method

Leave a reply