Java Method Return

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;/*  ww  w .  j  a  v a 2s  . c om*/
  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 .jav  a2s  . 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:





















Home »
  Java Tutorial »
    Java Language »




Java Data Type, Operator
Java Statement
Java Class
Java Array
Java Exception Handling
Java Annotations
Java Generics
Java Data Structures