Monday, May 26, 2025

Return types

 The next thing that comes up in a method signature (after the access modifier and the static flag) is the return type. At a high level, there are two return possibilities: nothing and something.


You might have a method that returns nothing, but it is never allowable to not have a listed return type (except in the case of a constructor). If your method returns nothing, the correct return type is void.  (Recall that we have “public static void main(String[] args)”). If your method returns void, you won’t return anything. You can have a “return” statement—more on that in a bit—in a void method, just as an “if I get here, stop and exit” condition, but there won’t be a value attached.

That early exit might look like

public class EarlyExitDemo {

    public void printPositive(int number) {

        if (number <= 0) {

            return;

        }

        System.out.println("The number is positive: " + number);

    }

}
 
Here, if the passed-in number is negative or zero, the program just gracefully exits by that “return” statement.

This is not required. Recall, again, HelloWorld written only in the main method, as simply as possible. The main method is void, and there is no return, even for an early exit as above:



 

public class HelloWorld {

    public static void main(String[] args) {

        System.out.println("Hello, World!");

    }

}  

However, if your method has some other declared return type—which can be any primitive or any object—then if you fail to return a value of that type, you will get an error.

Look at this code:

public class SimpleReturn {

    public int goodDoubleValue(int number) {

        return number * 2;

    }

}

This is correct. The return type expected is an integer, and we return 2 times an integer, which is an integer.

If instead the code had, for example, saved number * 2 into a variable but forgotten to return it, that would produce an error. Look at an example of that below:

public class SimpleReturn {

    public int badDoubleValue(int number) {

        int result = number * 2;

    }

}

When writing in an IDE, they can be especially helpful at flagging errors like this one!

No comments:

Post a Comment

Switch

 Other than if/if-else/if-else if-else and the ternary operator, there is yet another common and important conditional expression in Java th...