72. How does a method return a value?

The better way to implement volume( ) method in Box class is to compute the volume of the box and return the result to the method caller.

The following example is an improvised version to our previous program, with an enhancement in returning the volume result to the method caller:

Method returning volume will look like this: 

public double volume( )
    return width*height*depth;

Since the output of width*height*depth is of double type. We have mentioned double as return type i.e. double volume( ). Here we are returning the result as the calculated volume (i.e. width*height*depth).

Return result will be captured by a variable in 'ReturnCallingMethodDemo' class as shown below:

vol = box1.volume( );

Lets now do this on Eclipse IDE:

1. Launch Eclipse IDE, ensure that 'Third Project' Java project is available, modify the volume( ) method such that it returns a value as shown below -

2. Create a class named 'ReturnCallingMethodDemo' under third_pakage of Third Project as shown below:

3. Create two objects as instance of Box class as shown below:

4. Declare a variable of double type to store the value returned by the volume( ) method of Box class as shown below:

5. Assign values to the 'width', 'height' and 'depth' variables of box1 and box2 objects as shown below:

6. Call the volume methods and store the returned result of volume( ) method of Box class into a variable and print as shown below:

  7. Save the 'ReturnCallingMethodDemo' class and Run it as Java Application as shown below:

8. Observe that the output is displayed in console as shown below:

Without using variable 'vol' in the above example:

You can also print the return value of volume( ) method directly as shown below:

System.out.println("The value of box1 is "+ box1.volume( ) );

Instead of:

double vol;
vol = box1.volume( );
System.out.println("The value of box1 is "+ vol);

Both scenarios work as same.

Download this project:

Click here to download the project containing '' file. (You can import the downloaded project into Eclipse ID on your system)

Please comment below to feedback or ask questions.

How does a method intake parameters will be explained with an example in the next post.

No comments: