Uses of Return keyword in Java | Get value, Statement & Examples

Java return keyword is used in a method to get return value after execution is completed. In the method when the return statement executed, that time program will return to the code that invoked it.

It’s not a necessary method to have a return statement. For that, the method must be declared void and it doesn’t need to contain a return statement.

Return keyword in Java

Remember:-

  • The return statement is used to exit from the method.
  • If the method is void then return statement not allowed.
  • The return type and return value data type must be the same.
  • Return is a reserved keyword in Java i.e, you can’t use it as an identifier.
  • It can use for exit from a method, with or without a value.

Examples of Java return Keyword

We will check multiple examples:

1. Simple method return int value.

No logic or statements are in methods, just return an integer value.

Output: 90

2. Passing parameter for calculations

Let’s try the example where we will pass parameters 2 and perform the additional operation, then the method will return its value.

Output: 30

3. Returning String

To get a string as a return value you have to change return type and value to a string.

Output: Hello Developer

Q: What are the Uses of Return keyword in Java?

Answer: The return keyword can be used in two ways:-

  • To return a value to the caller method.
  • To stop the program execution.

Typically return is the last statement of a program. No other statement (other than statements in “finally block“) gets executed if they are after a return.

Q: How to write a method without a return value?

Answer: You have to declare the void method to don’t use a return statement. If you write a return statement with value in a method, it will show an error. But can use return keyword alone. See below example:-

With Return keyword:

Do comment if you have any doubts and suggestions on this tutorial.

Note: This example (Project) is developed in IntelliJ IDEA 2018.2.6 (Community Edition)
JRE: 11.0.1
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
macOS 10.14.1
Java version 11
All Java Retrun statement Example codes are in Java 11, so it may change on different from Java 9 or 10 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.