codescracker


java

Java Returning Objects



« Previous Tutorial Next Tutorial »


In Java, a method can return any type of data, including class types that you can create. For example, in the following Java program, the method incrByTen() returns an object in which the value of a is ten greater than it is in the invoking object.

Java Returning Objects Example

/* Java Program Example - Java Returning Objects
*  Returning an object */

class Test
{
    int a;
    
    Test(int i)
    {
        a = i;
    }
    
    Test incrByTen()
    {
        Test temp = new Test(a+10);
        return temp;
    }
}

public class JavaProgram
{   
    public static void main(String args[])
    {
        
        Test obj1 = new Test(2);
        Test obj2;
        
        obj2 = obj1.incrByTen();
        
        System.out.println("obj1.a : " + obj1.a);
        System.out.println("obj2.a : " + obj2.a);
        
        obj2 = obj2.incrByTen();
        
        System.out.println("obj2.a after second increase : " + obj2.a);
        
    }
}

When the above Java program is compile and executed, it will produce the following output:

returning objects in java

As you can see, each time the method incrByTen() is invoked, a new object is created, and a reference to it is returned to the calling routine.

The preceding program makes another important point i.e., since all the objects are dynamically allocated using the new operator/keyword, you don't need to worry about an object going out-of-scope because the method in which it was created terminates. The object will continue to exist as long as there is a reference to it somewhere in your program. When there are no references to it, the object will be reclaimed the next time garbage collection takes place.


« Previous Tutorial Next Tutorial »



Tools
Calculator

Quick Links
Signup - Login - Give Online Test