Codiqo

Learn Java · lesson 23 of 61 · about 8 minutes

Parameters and Return Values

Show amounts as money with a method that takes the cents as a parameter and returns the text with return.

What you'll learn

  • Declare parameters
  • Return a value
  • Use returned values in expressions

Cents as dollars

The desk keeps money in whole cents, and turning cents into $89.45 has been written out with / 100 and % 100 again and again. A method static String money(int cents) takes the cents as a parameter and hands the finished text back with return, so any line can just add money(paid).

Inputs and an output

static int area(int w, int h) { return w * h; } takes two ints and returns an int. Calling area(3, 4) copies 3 and 4 into w and h, and the call becomes the returned 12.

A method can have several returns; the first one reached ends it.

Methods that return

public class Main {
    static int area(int w, int h) {
        return w * h;
    }

    static String sign(int n) {
        if (n < 0) return "negative";
        if (n == 0) return "zero";
        return "positive";
    }

    public static void main(String[] args) {
        System.out.println(area(4, 3));
        System.out.println(area(2, 2) + area(1, 5));
        System.out.println(sign(-2) + " " + sign(0) + " " + sign(9));
    }
}

Output

12
9
negative zero positive

Step through a call: into the function and back

public class Main {
    public static void main(String[] args) {
        int a = square(3);
        System.out.println(a + 1);
    }

    static int square(int x) {
        return x * x;
    }
}

Output

10

Money as text

public class Main {
    public static void main(String[] args) {
        System.out.println("Bill: " + money(8945));
        System.out.println("Popcorn: " + money(450));
    }

    // an amount in cents, shown as dollars
    static String money(int cents) {
        return String.format("$%d.%02d", cents / 100, cents % 100);
    }
}

Output

Bill: $89.45
Popcorn: $4.50

Now try it yourself

This lesson is free in Codiqo, with 10 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.