Branching Statements

Return

🙋 Need help? Ask an expert now!

Another important branching statement in Java is the return statement, which we have already seen before when we covered methods. At any time in a method, the return statement is used to cause the whole method to return a certain value and ignore all the statements underneath it. The program belows shows an example of the count() method and a return statement inside a while loop.

ReturnStatementExample.java
package exlcode;

public class ReturnStatementExample {

  public static int exampleVariableOne = 100;

  public static void main(String[] args) {
    System.out.println(count());
  }

  public static String count() {
    while (exampleVariableOne > 0) {
      if (exampleVariableOne == 25) {
        return "exampleVariableOne is 25";
      }
      exampleVariableOne--;
    }
    // returns the statement below if exampleVariableOne
    // is never equal to 25
    return "exampleVariableOne is never equal to 25";
  }
}

As you can see after running the code above, return breaks the loop and exits the method immediately after it is called. The statement return "exampleVariableOne is never equal to 25"; is never called because exampleVariableOne will eventually reach 25 as it decreases from 100 to 0.

The return statement is useful because it saves time and makes the program run faster by returning the output of method without executing unnecessary code and loops. It is good practice to always have a return statement after the for/while loop in case the return statement inside the for/while loop is never executed. Otherwise, a compile-time error will occur because the method cannot return nothing (unless it has the Java reserved word "void" in the method header).

Application Question

Fill in the blank below:

public static ___ getGrade(double score) {
              if (score >= 90.0)
                return 'A';
              else if (score >= 80.0)
                return 'B';
              else if (score >= 70.0)
                return 'C';
              else if (score >= 60.0)
                return 'D';
              else
                return 'F';
              }
            }