In Java methods have "return" statements. A "void
" method does not need to have a return, but it can include one to exit early. Other methods must return the correct type.
In a return statement, we evaluate expressions—and as part of this evaluation, other methods may run. Types must match, or an error occurs. Code after a return may become unreachable.
We can return a single value. But often we want a more complex return statement—we use an expression after the return keyword. Here an expression that multiplies two values.
ComputeSize()
receives 2 arguments, both of type int
. In the return expression, the two numbers are multiplied.public class Program { static int computeSize(int height, int width) { // Return an expression based on two arguments (variables). return height * width; } public static void main(String[] args) { // Assign to the result of computeSize. int result = computeSize(10, 3); System.out.println(result); } }30
In a return statement, we can invoke another method. In this example, we return the result of cube()
when getVolume()
returns.
Math.pow
, a built-in mathematics method.public class Program { static int cube(int value) { // Return number to the power of 3. return (int) Math.pow(value, 3); } static int getVolume(int size) { // Return cubed number. return cube(size); } public static void main(String[] args) { // Assign to the return value of getVolume. int volume = getVolume(2); System.out.println(volume); } }8
void
methodIn a void
method, an implicit (hidden) return is always at the end of the method. But we can specify a return statement (with no argument) to have an early exit.
public class Program { static void displayPassword(String password) { // Write the password to the console. System.out.println("Password: " + password); // Return if our password is long enough. if (password.length() >= 5) { return; } System.out.println("Password too short!"); // An implicit return is here. } public static void main(String[] args) { displayPassword("furball"); displayPassword("cat"); } }Password: furball Password: cat Password too short!
Boolean
We can use an expression to compose a boolean return value. This is a powerful technique—we combine several branches of logic into a single statement.
isValid
is a boolean. Both logical conditions must be satisfied for isValid
to return true.public class Program { static boolean isValid(String name, boolean exists) { // Return a boolean based on the two arguments. return name.length() >= 3 && exists; } public static void main(String[] args) { // Test the results of the isValid method. System.out.println(isValid("green", true)); System.out.println(isValid("", true)); System.out.println(isValid("orchard", false)); } }true false false
A method that is supposed to return a value (like an int
) must return that value. Otherwise a helpful compilation error occurs.
public class Program { static int getResult(String id) { // This method does not compile. // ... It must return an int. if (id.length() <= 4) { System.out.println("Short"); } } public static void main(String[] args) { int result = getResult("cat"); System.out.println(result); } }Exception in thread "main" java.lang.Error: Unresolved compilation problem: This method must return a result of type int at Program.getResult(Program.java:3) at Program.main(Program.java:13)
This is a common programming problem. To return two values, we can use a class
argument—then we set values within that class
.
class
. Then those methods simply modify fields of the class
.class Data { public String name; public int size; } public class Program { static void getTwoValues(Data data) { // This method returns two values. // ... It sets values in a class. data.name = "Java"; data.size = 100; } public static void main(String[] args) { // Create our data object and call getTwoValues. Data data = new Data(); getTwoValues(data); System.out.println(data.name); System.out.println(data.size); } }Java 100
This is a fatal error in Java. If code cannot be reached, we get a java.lang.Error
. To fix this program, we must remove the "return" or the final, unreachable statement.
public class Program { public static void main(String[] args) { System.out.println("Hello"); return; System.out.println("World"); } }Exception in thread "main" java.lang.Error: Unresolved compilation problem: Unreachable code at Program.main(Program.java:9)
We cannot assign a variable to void
method. This returns in a "type mismatch" error. Void means "no value." To fix, remove the variable assignment.
public class Program { static void test() { System.out.println(123); } public static void main(String[] args) { // This does not compile. // ... We cannot assign to a void method. int result = test(); } }Exception in thread "main" java.lang.Error: Unresolved compilation problem: Type mismatch: cannot convert from void to int at Program.main(Program.java:11)
In my tests, I found that the JVM does a good job of inlining methods. So if we return a statement that evaluates into another method call, this causes no apparent slowdown.
The return keyword signals an end to a method. It accepts an argument of a type that matches the method's signature. In a void
method, we use a no-argument return.