Java Method Return

In this chapter you will learn:

  1. How to return from a method
  2. Syntax for return value from a method
  3. Example - How to return a value from a method
  4. Example - How to return an object from a method

Description

A method in a class can return a value with the return statement.

Syntax

Methods that have a return type other than void return a value to the calling routine using the following form of the return statement:


return value; 

Here, value is the value returned.

Example

We can use return statement to return a value to the callers.

 
class Rectangle {
  int width;//from   www  . jav a2  s  .c o m
  int height;

  int getArea() {
    return width * height;
  }
}

public class Main {

  public static void main(String args[]) {
    Rectangle mybox1 = new Rectangle();
    int area;
    mybox1.width = 10;
    mybox1.height = 20;

    area = mybox1.getArea();
    System.out.println("Area is " + area);

  }
}

The output:

In this line the return statement returns value from the getArea()method. And the returned value is assigned to area.


area = mybox1.getArea();

The actual returned data type must be compatible with the declared return type . The variable receiving the returned value (area) must be compatible with the return type.

The following code uses the returned value directly in a println( ) statement:


System.out.println("Area is " + mybox1.getArea());

Example 2

A method can return class types.

 
class MyClass {/*  ww  w  .  ja  v a2 s  .  c  o  m*/
  int myMemberValue = 2;
  MyClass() {
  }
  MyClass doubleValue() {
    MyClass temp = new MyClass();
    temp.myMemberValue = temp.myMemberValue*2;
    return temp;
  }
}

public class Main {
  public static void main(String args[]) {
    MyClass ob1 = new MyClass();
    ob1.myMemberValue =2;
    MyClass ob2;

    ob2 = ob1.doubleValue();
    System.out.println("ob1.a: " + ob1.myMemberValue);
    System.out.println("ob2.a: " + ob2.myMemberValue);

    ob2 = ob2.doubleValue();
    System.out.println("ob2.a after second increase: " + ob2.myMemberValue);
  }
}

The output generated by this program is shown here:

Next chapter...

What you will learn in the next chapter:

  1. What are parameters for
  2. Syntax for Java Method Parameters
  3. How to add parameters to a method
  4. How to use class type as method parameters