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 does 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 does 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 evaluates to either true or false. If the condition evaluates to true, the body of the if executes. If the condition evaluates to false, the body of the else executes.

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 executes. When a return statement executes, the method immediately terminates. The statement return 1; executes 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 does not return a value of type int.

Although a programmer can tell that the return -1; statement can 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 does not compile because the println statement is unreachable. The method always executes a return statement, and terminates, 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