Java - Class Method Return

What is method return?

Method return statement returns a value from a method.

It returns the control to the caller of the method.

return type

Here are the two types of the return statement:

If a method returns a value, <an expression> must evaluate to a data type, which is compatible with the return type of the method.

return <an expression>;

or If method's return type is void

return;

Example

The following code shows how to assign the returned value to a variable.

Demo

public class Main {
  public static void main(String[] args) {
    int sum = add(2, 4);
    System.out.println(sum);/*  ww w  . j  a  va  2  s . c o m*/
  }

  static int add(int n1, int n2) {
    int sum = n1 + n2;
    return sum;
  }
}

Result

Related Topics