In Java, there are often situations where the developers are required to return values from the methods to analyze the real-time output of the applied target functionality. In such situations, the “return” reserved keyword comes into effect which helps in exiting from a method with or without returning a value.
It is mainly used within the function bodies to stop the function’s execution at a target point. The return type, however, can be a primitive data type such as “int”, “float”, “double”, a reference type, or a “void” type.
Contents Overview
- What is the Java “return” Keyword?
- Prerequisites Before Using the “return” Keyword
- Why Use “return” Instead of “print” in Java?
- How to Use the Java “return” Keyword?
- Returning a Value Via Method Using the “return” Keyword
- Method Not Returning a Value
What is the Java “return” Keyword?
The Java “return” keyword is used to complete the method’s execution and can be used to return a value (can be of various data types) from a method. It implies that the method does not execute further after the specified “return” keyword.
Note: The “void” keyword specified as the “return” type of a method does not return any value.
Prerequisites Before Using the “return” Keyword
The following prerequisites should be considered before returning from a function:
- The return type of the method should be compatible with the type of the value being returned.
- The sequence in which the parameters are specified in the method should be passed to the method in the same sequence while accessing it.
Why Use “return” Instead of “print” in Java?
The “print” statement prints a string representation of the code that can be custom-specified. On the other hand, the “return” statement represents how a function returns a value originally, thereby signifying the behavior of the function.
How to Use the Java “return” Keyword?
The “return” keyword can be used in the following two scenarios:
- Returning a Value Via Method.
- Method Not Returning a Value.
Case 1: Returning a Value Via Method Using the “return” Keyword
The following examples make use of the “return” keyword to return values.
Example 1: Applying the Java “return” Keyword to Return a Value
This example explains the basic use of the “return” keyword to return an integer value:
package jbArticles;
public class Return {
int ret(int x) {
return x;
}
public static void main(String[] args) {
System.out.println("Returned Value -> " +new Return().ret(3));
}}
In this code, consider the following steps:
- In the public class “Return”, define a function “ret()” of the “int” return type that returns the passed integer value via the “return” keyword.
- After that, create a class instance using the “new” keyword and the “Return()” class constructor.
- Also, invoke the defined function by passing the given integer value to be returned.
Output
This output confirms that the passed integer value is returned.
Example 2: Applying the Java “return” Keyword to Return Multiple Data Types Values
The following code uses the “return” keyword to return the values of multiple data types using the same method name:
package jbArticles;
public class Return {
char ret(char x) {
return x;
}
String ret(String x) {
return x;
}
float ret(float x) {
return x;
}
double ret(double x) {
return x;
}
public static void main(String[] args) {
System.out.println("Returned Value -> " +new Return().ret(2.34));
}}
The code explanation is as follows:
- Declare multiple functions with the same name having different return data types.
- These functions accept the corresponding value as their argument and return that value.
- Finally, create a class instance and invoke the function once such that it is compatible with all the data type values since the function name is the same.
Output
From this output, it can be observed that the specified values of multiple data types are returned accordingly.
Note: Different function names can also be specified while declaration and the relevant values can be passed to these functions by invoking them separately as per the requirements.
Example 3: Applying the Java “return” Keyword to Return the Sum of Values
In this demonstration, the “return” keyword can be used to get the sum of the passed values via a user-defined function:
package jbArticles;
public class Return {
int sum(int a, int b) {
int c = a + b;
return c;
}
public static void main(String[] args) {
System.out.println("Sum of Values -> " +new Return().sum(3, 7));
}}
In this snippet of code:
- Within the public class, define the function “sum()” that takes the two values as its arguments and returns their sum.
- After that, likewise, create a class instance and access the function by passing the given two values to return their sum.
Output
Here, the sum of the values as an integer is returned appropriately.
Case 2: Method Not Returning a Value
In this case, the situations will be discussed in which the methods cannot return a value which are listed below:
- The Method With “void” Return Type Not Using “return” Keyword.
- The Methods With “void” Return Type that Exit Control From the Method.
Example 1: The Method With “void” Return Type Not Using “return” Keyword
Since the methods used with the “void” return types do not return a value, therefore, the “return” keyword is not required and hence, no value is returned, as demonstrated below:
package jbArticles;
public class Return {
void sum(int a, int b) {
int c = a + b;
System.out.println("Sum of Values -> "+c);
}
public static void main(String[] args) {
new Return().sum(3, 7);
System.out.println("No 'return' keyword is Used!");
}}
Here, a method prints the sum of the passed values rather than returning them. After that, in “main”, similarly, create a class instance and invoke the defined function that prints the sum.
Output
Note: In the above type scenarios, although the “return” keyword is not required, it can be specified with the methods having the return type as “void” like “return;” which returns nothing.
Example 2: The Methods With “void” Return Type that Exit Control From the Method
In this demonstration, the “return” keyword is specified in the “void” method such that the control is exited from the method upon the satisfied condition:
package jbArticles;
public class Return {
void sum(int a, int b) {
int c = a + b;
if(c > 15)
return;
c++;
}
public static void main(String[] args) {
new Return().sum(3, 7);
System.out.println("The 'void' Method cannot return!");
}}
In this block of code, consider the following explanation:
- In the class definition, similarly declare the method “sum()” that gets the sum of the passed values.
- After that, specify the condition such that if the condition in the “if” statement becomes true, the control exits from the method.
- In the “main”, invoke the function via class instance and pass the given values whose sum is to be returned.
Output
Here, it can be seen that since the function’s return type is “void”, no value is returned. Also, upon the “true” condition, the control exits from the function, and the rest of the statement is not executed.
In the below scenario, specifying a value with the “return” keyword can also not return any value since the return type of the method is “void”:
Scenario Example 1: Specifying the Java “return” Keyword at the End of the Method
The “return” keyword should not always be the last statement. Instead, it should be the last statement in the method for the method to execute. Below is the demonstration:
package jbArticles;
public class Return {
void sum(int a, int b) {
int c = a + b;
if (c < 200)
return;
else
c++;
}
public static void main(String[] args) {
System.out.println(new Return().sum(3, 7));
System.out.println("The 'void' Method cannot return!");
}}
The code explanation is as follows:
- Repeat the steps for defining a function that returns the sum of values.
- After that, a condition is specified and upon the true condition, the “return” keyword is specified but not as a last statement in the method, therefore the method cannot execute.
- It is such that there is no logic in defining any further code after the “return” statement.
- Otherwise, the “else” statement executes.
- In “main”, access the defined function by passing the stated values as its arguments.
Output
Here, it can be seen that an error is returned since the void function is being invoked and printed.
Note: Without specifying the “print” statement, the second print statement will execute only since the method’s return type is “void”.
Scenario Example 2: Using the “return” Keyword to Make the Remaining Code Unreachable
In this case, the “return” keyword is specified such that the remaining code becomes unreachable:
package jbArticles;
public class Return {
void temp(int x) {
return;
x++;
}
public static void main(String[] args) {
new Return().temp(3);
System.out.println("The 'void' Method cannot return!");
}}
According to these lines of code, within the class function definition, the “return” keyword is specified.
Since the function’s return type is “void”, it returns nothing but the remaining code i.e., “x++” becomes unreachable as the “return” keyword should be specified at the end of the method, as discussed.
Output
In the above output, it is verified that after the specified “return” keyword, the remaining code becomes unreachable.
Bonus Example: Using the “return” Keyword as a “break” Statement
The below example uses the discussed keyword as a “break” statement such that upon any of the satisfied cases/statements, the corresponding block executes:
package jbArticles;
public class Return {
public String ret(int a){
if(a < 5)
return "Number less than 5";
if(a > 5 && a<20)
return "Number greater than 5";
return "Number greater than or equal to 100"; }
public static void main(String[] args) {
System.out.println(new Return().ret(8));
}}
In this code, a function named “ret()” is defined as having the return type as “String” that takes in a value and checks for multiple conditions. Also, the default case i.e., the last “return” statement is returned if neither of the specified conditions are unsatisfied.
Output(Satisfied Condition)
As seen, the first satisfied condition is invoked.
Output(Default Condition)
Here, the default condition is invoked upon specifying the integer i.e., “35” that does not meet either of the applied conditions.
Conclusion
The Java “return” keyword is used to complete the method’s execution and can be used to return a value of various data types via a method. This keyword can be used by a method to return a value or to not return any value at all.
It can also be used as an alternative to the “break” statement to invoke the relevant statement or the “default” statement in case all the conditions are unsatisfied.