This post will describe the working of the “return” statement with some examples.
- What does return do in java?
- Basic Syntax
- How does a method return a value in Java?
So, let’s get started!
What does return do in java?
The return statement performs the below-listed functionalities in Java:
- The return statement in Java is used to come out from a method.
- The return value depends on the method’s return type.
- It is impossible to use the return keyword in a method that is declared with a void keyword.
- The method’s return type and the value to be returned must be matched.
Basic Syntax
Let’s consider the below snippet to understand the basic syntax of the return statement:
How does the return statement work in a method?
Let’s learn how to return a value in java with the help of some examples:
Example: how to return an integer from a method?
int sumValue() {
return 14+22;
}
public static void main(String[] args) {
ExampleClass obj = new ExampleClass();
System.out.println("Sum of two Values: " + obj.sumValue());
}
}
In this example program, firstly, we created a method named “sumValue()” and specified its return type as “int”. The method will return the sum of two integer values using the return statement:
The output verified that when we invoked the sumVlaue() method, it returned the sum of two integer values.
Example: Incompatible type Error
String sumValue() {
return 14+22;
}
public static void main(String[] args) {
ExampleClass obj = new ExampleClass();
System.out.println("Sum of two Values: " + obj.sumValue());
}
}
In this coding example, all the code is the same as in the previous example except the method’s return type. The method’s return type is a string; however, the returning values are integer type so we will encounter the following compile-time error:
This time, we encountered an incompatible type error at compile-time. This means the method’s return type and the value passed with the return statement must be matched.
Conclusion
In java, the return statement is used to return some value on completion of the block execution. The returned value depends on the method’s return type. The method’s return type and the value to be returned must be matched. This write-up explained what return does in Java with the help of some examples.