How to Use the return Keyword in Java

Roger Winter



The return keyword is probably the most underused one in Java. This feature is available in almost every programming language and allows the programmer to specify a return value of the current method.

person using java return on a computer in an office

In this post, we’ll cover the various use cases of the return keyword, along with examples, and help you take advantage of this feature. Let’s dive in.

Download Now: An Introduction to Java & JavaScript

What is the Java return keyword?

In Java, the return keyword returns a value from a method. The method will return the value immediately when the keyword is encountered. This means that the method will not execute any more statements beyond the return keyword, and any local variables created in the method will be discarded.

Developers can use the return keyword with or without a value. If a value is specified, it will be returned to the caller. Otherwise, a null value will be returned.

There are a few best practices to adhere to when using return — let’s dive deeper into how this keyword works in your functions and explore the types of data you can return.

How to Use return in Java

A return statement is like a break statement in a for loop, in that it redirects the program outside of that block’s execution. In other words, a return statement immediately exits the current method and transfers control back to the caller.

This is similar to how a break statement immediately exits a for loop and transfers control back to the enclosing code block. To understand how this works, consider the following example:

public String function(int a){ if(a<10) return "Number less than 10"; if(a<100) return "Number greater than 10 but less than 100"; a = a * 10; return "Number greater than or equal to 100"; }

In the code above, if you pass the number 8 to the function, it will return the string “Number less than 10” and move on to the function’s caller. Similarly, if parameter a is less than 100, the function returns “Number greater than 10 but less than 100.” If the parameter is greater than or equal to 100, the program multiplies a by 10 and returns “Number greater than or equal to 100.”

Every Java method must include a return type in its declaration. If there’s nothing to return, use void as the return type. There are several return types classified in one of two ways. Primitive types like int, float, and double represent raw values, whereas non-primitive types can represent things like classes, arrays, or interfaces.

class DisplayClass{ private String message = null; public DisplayClass(string message){ this.message = message; } public void display(){ System.out.println(message); } } public class Main{ // this function will return an instance of a DisplayClass. public static DisplayClass function(String message){ return new DisplayClass(message); } public static void main(String[] args){ DisplayClass obj = function("Hello World"); obj.display(); } }

Above, we call the method function("Hello World"). This method takes a string as an argument and returns an instance of the DisplayClass object, through which we call the display() method. This shows that we can also return non-primitive types (e.g., a class or interface) from a method.

If a function is declared to return a specific type of data, then it must return only data of that type. Otherwise, the program will encounter a compile time error. This is because the return type of a method is part of its signature, and the signature of a method must match the signature of the variable used to store its return value.

For example, if the method’s return type is an integer, you can’t return a string.

public int function(){ // this will show compiler error // return "1"; return 1; // This will work. } // while calling this function // this will show a compile-time error // String s = function(); // This will work. int n = function();

Additionally, you must pass the parameters to the method in the same sequence in which they’re accepted by the method. This is because the method will only be able to access the parameters in the order in which they’re received. If the parameters are not passed in the correct sequence, the method will not be able to use them properly.

Consider the example below:

// Function to add 1 to first parameter & multiply it with second public int multiply(int a, int b){ int first = a+1; int ans = first*b; return ans; } // while calling this function // here a = 8, and b = 5. multiply(8, 5);

Now, if you don’t pass a and b in the right sequence, you might run into unexpected output.

Furthermore, remember to use the void type when your function doesn’t return a value. Consider the following example, which has a function with an int argument that you’re printing:

public void printValue(int a){ System.out.println(a); }

Demonstration with Simple Arithmetic

Consider a function that takes two integer arguments and returns the largest of the two, as shown below:

public int max(int a, int b){ if(a>b) return a; return b; } // while calling this function int ans = max(5, 10); System.out.println(ans); // output will be 10.

Similarly, you can perform some arithmetic operations on integers to obtain the appropriate results. For example:

public int Sum(int a, int b){ return a+b; } int ans = Sum(100, 200); // This will return the sum, 300.

Java return Best Practices

When it comes to the Java return keyword, there are a few best practices to keep in mind.

First, return a value from a method whenever possible. This includes returning void if there’s nothing to return. This will help to ensure that your code is reliable and easy to debug.

Next, ensure that you return the correct data type from a method. If a method expects an integer return type, be sure that your method returns an integer value.

Finally, it’s always wise to document what a method is returning so that other developers can easily understand your code.

This final example shows all of these best practices in one simple function — can you identify them all?

public int doubleOdd(int n){ /* Checks if the number is odd. If true, it doubles it, otherwise returns the number. @returns the number if even, otherwise it doubles int */ if(n%2 == 0) return n; int convert = n*2; return convert; // returning the same data type } // when we call this function int a = convert(5); // a = 10 int b = convert(6); // b = 6

By following these simple best practices when using the return keyword, you can help ensure that your codebase is reliable and easy to maintain.

return In Java: Know the Fundamentals

The return keyword stops the execution of a function and returns the desired output. Even if there’s no value to return, it will use void as a return type. Furthermore, you can use return without a value to stop the execution of a function.

When implementing return statements, remember that the method’s return type and the type of value it returns must match the variable type where the returned value is stored.

New Call-to-action

Topics: Java

Related Articles

We're committed to your privacy. HubSpot uses the information you provide to us to contact you about our relevant content, products, and services. You may unsubscribe from these communications at any time. For more information, check out our Privacy Policy.

Learn more about one of the world's most popular programming languages.