Java returning value from method



Returning Value From the Method :

  1. We can specify return type of the method as “Primitive Data Type” or “Class name”.
  2. Return Type can be “Void” means it does not return any value.
  3. Method can return a value by using “return” keyword.

Returning-Value-from-the-Method

Live Example : Returning Value from the Method

class Rectangle {
  int length;
  int breadth;

  void setLength(int len)
  {
  length = len;
  }

  int getLength()
  {
  return length;
  }

}

class RectangleDemo {
  public static void main(String args[]) {

  Rectangle r1 = new Rectangle();

  r1.setLength(20);

  int len = r1.getLength();

  System.out.println("Length of Rectangle : " + len);

  }
}

Output :

C:Priteshjava>java RectangleDemo
Length of Rectangle : 20

There are two important things to understand about returning values :

  1. The type of data returned by a method must be compatible with the return type specified by the method. For example, if the return type of some method is boolean, you could not return an integer.
boolean getLength()
  {
  int length = 10;
  return(length);
  }
  1. The variable receiving the value returned by a method (such as len, in this case) must also be compatible with the return type specified for the method.
int getLength()
  {
  return length;
  }

boolean len = r1.getLength();
  1. Parameters should be passed in sequence and they must be accepted by method in the same sequence.
void setParameters(String str,int len)
  {
  -----
  -----
  -----
  }

 r1.setParameters(12,"Pritesh");

Instead it should be like –

void setParameters(int length,String str)
  {
  -----
  -----
  -----
  }

 r1.setParameters(12,"Pritesh");