Return Values

Returning a Result

Example

Use a return type instead of void and send a value back with return.

public class Main {
    static int square(int n) {
        return n * n;
    }

    static double gst(double amount) {
        return amount * 0.18;
    }

    static boolean isEven(int n) {
        return n % 2 == 0;
    }

    static String grade(int marks) {
        if (marks >= 75) return "Distinction";
        if (marks >= 40) return "Pass";
        return "Fail";              // every path must return a value
    }

    public static void main(String[] args) {
        int s = square(9);
        System.out.println(s);
        System.out.println(gst(1000) + 1000);
        System.out.println(isEven(7));
        System.out.println(grade(82) + ", " + grade(55) + ", " + grade(20));
        System.out.println(square(square(2)));   // use a result as an argument
    }
}

Output

81
1180.0
false
Distinction, Pass, Fail
16

Rules

  • return ends the method immediately.
  • A non-void method must return a value of the declared type on every path, or it will not compile (missing return statement).
  • A void method may use a bare return; to exit early.
  • A method returns only one value. Return an array or an object to send back more.

Exercise: Write a method max3(int a, int b, int c) that returns the largest of three numbers.

Show answer
static int max3(int a, int b, int c) {
    int max = a;
    if (b > max) max = b;
    if (c > max) max = c;
    return max;
}