Case 1: Methods returning a value
For methods that define a return type, return statement must be immediately followed by return value.
Example:
// Java Program to Illustrate Usage of return Keyword
// Main method
class GFG {
// Method 1
// Since return type of RR method is double
// so this method should return double value
double RR(double a, double b) {
double sum = 0;
sum = (a + b) / 2.0;
// Return statement as we already above have declared
// return type to be double
return sum;
}
// Method 2
// Main driver method
public static void main(String[] args)
{
// Print statement
System.out.println(new GFG().RR(5.5, 6.5));
}
}
Output
6.0
Output explanation: When we are calling a class GFG method that has return sum which returns the value of sum and that’s value gets displayed on the console.
Time Complexity of the above Method:
Time Complexity: O(1)
Auxiliary Space : O(1)
return keyword in Java
In Java, return is a reserved keyword i.e., we can’t use it as an identifier. It is used to exit from a method, with or without a value. Usage of return keyword as there exist two ways as listed below as follows:
- Case 1: Methods returning a value
- Case 2: Methods not returning a value
Let us illustrate by directly implementing them as follows:
Contact Us