The content below assumes familiarity with Writing and calling methods, Methods with parameters, and Methods with return values.

Method that fails to return a value in all paths

public static int someMethod(int a)
{
    if(a >= 0)
        return 0;

    if(a < 0)
        return 1;
}

The intent of someMethod is to return 0 if the value of a is at least 0 or 1 if the value of a is negative.

Method someMethod will not compile. The header indicates that someMethod returns an int. This means that the method must return a value of type int in all possible paths through the code. All of the return statements are inside conditional statements. If all of the conditions evaluate to false, the method will not return a value.

It does not matter whether all of the conditions can actually evaluate to false. The Java compiler has no way to determine that, as in this case, it is impossible for all of the conditions to evaluate to false.

Option 1 to correct someMethod

public static int someMethod(int a)
{
    if(a >= 0)
        return 0;
    else
        return 1;
}

The condition a >= 0 will evaluate to either true or false. If the condition evaluates to true, the body of the if will execute. If the condition evaluates to false, the body of the else will execute.

Option 2 to correct someMethod

public static int someMethod(int a)
{
    if(a >= 0)
        return 0;
    
    return 1;
}

If the condition evaluates to true, the body of the if will execute. When a return statement executes, the method immediately terminates. The statement return 1; will execute only if the condition evaluates to false.

Option 3 to correct someMethod

public static int someMethod(int a)
{
    if(a >= 0)
        return 0;

    if(a < 0)
        return 1;
    
    return -1;
}

The addition of the statement return -1; at the bottom satisfies the Java compiler. There is no longer a path through the method that will not return a value of type int.

Although a programmer can tell that the return -1; statement will never execute, the Java compiler has no way to determine that.

Method with unreachable code

public static int someMethod(int a)
{
    if(a >= 0)
        return 0;
    else
        return 1;
    
    System.out.println("hi");
}

someMethod will not compile because the println statement is unreachable. The method will have already executed a return statement, and terminated, prior to the println statement.

void method with return statement

public static void someMethod(int a)
{
    if(a >= 0)
        return;
    
    System.out.println("hi");
}

public static void main(String[] args)
{
    someMethod(5);
    someMethod(-10);
}

The code prints "hi" a single time (from the call someMethod(-10);).

Although a void method cannot return a value, it can return (end). In someMethod, if a >= 0, the method terminates (without executing the println statement).

Comments

Comment on Return statements