Syntax for Method Creation
This is the general form of a method:
type methodName(parameter-list) {
// body of method
}
type
specifies the returned type.
parameter-list
is a sequence of type and identifier pairs separated by commas.Return statement
return statement has the following form:
return value;
value
is the returned value.
Adding a Method to the Class
Add a method to Box,as shown here:
class Box {
int width;
int height;
int depth;
void calculateVolume() {
System.out.print("Volume is ");
System.out.println(width * height * depth);
}
}
public class Main {
public static void main(String args[]) {
Box mybox1 = new Box();
mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;
mybox1.calculateVolume();
}
}
This program generates the following output:
Volume is 3000
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());
Returning Objects
A method can return class types.
class MyClass {
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:
ob1.a: 2
ob2.a: 4
ob2.a after second increase: 4