Saturday, 31 January 2015

More About the Java Return Statement

The return statement does not have to pass a value back at all. It can just be used to return control to the calling program. Once a return statement has been executed, the code which follows it is not executed. You can see what I mean in the example below:

andrew@UBUNTU:~/Java$ cat Number_Check.java
public class Number_Check
  {
  public void check_number(int a)
    {
    if (a < 10)
      {
      System.out.println(a + " < 10");
      return;
      }
//  The next line is ignored if the number supplied
//  is less than 10:
    System.out.println(a + " >= 10");
    }
  }
andrew@UBUNTU:~/Java$ javac Number_Check.java
andrew@UBUNTU:~/Java$


andrew@UBUNTU:~/Java$ cat Number_Check_Test.java
class Number_Check_Test
  {
  public static void main(String args[])
    {
    Number_Check x = new Number_Check();
    x.check_number(9);
    x.check_number(10);
    x.check_number(11);
    }
  }
andrew@UBUNTU:~/Java$ javac Number_Check_Test.java
andrew@UBUNTU:~/Java$ java Number_Check_Test
9 < 10
10 >= 10
11 >= 10
andrew@UBUNTU:~/Java$


However, if the compiler sees code which will NEVER execute, it returns a compilation error:

andrew@UBUNTU:~/Java$ cat Another_Number_Check.java
public class Another_Number_Check
  {
  public void check_number(int a)
    {
    if (a < 10)
      {
      System.out.println(a + " < 10");
      return;
      }
    else
      {
      System.out.println(a + " >= 10");
      return;
      }
    System.out.println("This line is ignored");
    }
  }
andrew@UBUNTU:~/Java$ javac Another_Number_Check.java
Another_Number_Check.java:15: unreachable statement
    System.out.println("This line is ignored");
    ^
1 error
andrew@UBUNTU:~/Java$