Mega Code Archive

 
Categories / Java Book / 002 Class
 

0139 Returning a Value

We can use return statement to return a value to the callers. class Rectangle { int width; 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: Area is 200 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());