Java Method Return
In this chapter you will learn:
- How to return from a method
- Syntax for return value from a method
- Example - How to return a value from a method
- Example - How to return an object from a method
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;//from www . jav a2 s .c o m
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 . ja v a2 s . 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:
Next chapter...
What you will learn in the next chapter:
- What are parameters for
- Syntax for Java Method Parameters
- How to add parameters to a method
- How to use class type as method parameters
Java Object
Java Object Reference Variable
Java Methods
Java Method Return
Java Method ParametersJava Class Constructors
Java Default Constructor
Java Constructor Parameters
Java this Keyword
Java static keyword
Java Method Overload
Java Constructors Overload
Java Method Argument Passing
Java Method Recursion
Java Nested Class
Java Anonymous Classes
Java Local Classes
Java Member Classes
Java Static Member Classes
Java Class Variables
Java main() Method
Java Class Inheritance
Java super keyword
Java Method Overriding
Java Constructor in hierarchy
Polymorphism
Java final keyword
Java Abstract class
Java Class Access Control
Java Package
Java Packages Import
Java Interface
Java Interface as data type
Java interface as build block
Java instanceof operator
Java Source Files