Skip to content
wannacode

Parameters and return

Problem

One receipt, different totals

You want a method that prints the last line of the receipt: "Total: €…". But the total is different for every order.

The methods from the last lesson always print the same thing. A method printTotal() has no way to know the total. You do not want a separate method for every total either. You need a way to pass the total to the method when you call it.

The idea

Parameters: what the method gets

In the parentheses, declare what the method expects: a type and a name. That is a parameter. Inside the method it is an ordinary variable.

When you call it, you put the value in the parentheses. That value is called an argument.

static void printTotal(double total) {
System.out.println("Total: €" + total);
}
printTotal(12.5);
printTotal(4.2);
Output
Total: €12.5
Total: €4.2

double total is the parameter. 12.5 and 4.2 are the arguments. There is one method, and it prints different totals.

If there are several parameters, you separate them with commas. The arguments are passed in the same order.

Try it

By position, not by name

What will the program print?

static void printLine(String item, int qty) {
System.out.println(item + ": " + qty + " pcs");
}
String coffee = "Coffee";
int qty = 3;
printLine(coffee, 2);
Answer

Problem

Why did the price not go down?

You have written a method for a 10% discount and called it:

static void applyDiscount(double price) {
price = price * 0.9;
}
double price = 100;
applyDiscount(price);
System.out.println(price); // 100.0
Output
100.0

The price is still 100. The method gives no error, and yet the discount is not there. Where did it go?

See it

The method gets a copy

static void applyDiscount(double price) {
price = price * 0.9;
}
double price = 100;
applyDiscount(price);
System.out.println(price); // 100.0
Step by step, in words
  1. In main there is a variable price = 100.
  2. You call applyDiscount(price): new memory is set aside for the method.
  3. The value is copied into its parameter price.
  4. The method lowers its copy: 100 * 0.9 = 90.
  5. The method ends and its memory goes away, along with the copy.
  6. And price in main is still 100.

When you call it, the method does not get the variable price itself, but a copy of its value. It lowers the copy. When the method ends, its memory goes away, and the copy goes with it. This is called pass by value.

The two variables have the same name (price) on purpose: that is exactly what confuses people in practice. The name does not matter. Every method has its own variables.

The idea

return: the method returns a result

The fix is for the method to return the new price. Before the name, instead of void, you write the type of the result (double), and in the body you write return and the value.

static double applyDiscount(double price) {
return price * 0.9;
}
double price = 100;
price = applyDiscount(price);
System.out.println(price); // 90.0
Step by step, in words
  1. In main: price = 100.
  2. You call applyDiscount(price): memory is set aside for the method.
  3. The value is copied into the parameter price.
  4. return price * 0.9: the result is 90.
  5. The result goes back to main and is stored in price.
  6. Now price in main is 90.

The call applyDiscount(price) is now a value. You can store it in a variable (as here), print it or calculate with it.

More precisely, if you are curious
  • In a void method you can also write return; (with no value). It just ends the method.
  • In Java, arguments are always passed by value. With objects (the "Classes and objects" module), what gets copied is the link to the object, so changes there are visible outside too. We will see that then.

Try it

What is the result?

The method works out a 20% VAT on the price. What type should go in the blank?

static  vat(double price) {
    return price * 0.2;
}

Try it

Returned, but lost

What will the program print?

static int reserve(int seats) {
seats = seats - 2;
System.out.println("inside: " + seats);
return seats;
}
int seats = 10;
reserve(seats);
System.out.println("outside: " + seats);
Answer

The idea

return ends the method

The shop does not charge for delivery on orders of €50 or more. Otherwise delivery is €4.99:

static double shippingCost(double total) {
if (total >= 50) {
return 0;
}
return 4.99;
}
System.out.println(shippingCost(62.0));
System.out.println(shippingCost(18.5));
Output
0.0
4.99

As soon as it reaches return, the method ends right away. That is why at €62 the second return does not run, and we do not need an else.

A method with a result has to return a value on every path. If you remove the last line, the program does not compile: "missing return statement".

Try it

Find the bug

Club members get a 10% discount, and everyone else pays the full price. But everyone gets the discount. Which line is the bug on?

Pick the line with the bug.

Exercise

Methods that calculate

Solve the tasks in your editor. Each method gets what it needs as parameters and returns the result. The printing happens in main.

1. Average. The method average(int[] values) returns the average of the numbers in the array. In main, read from the keyboard how many numbers there are, then the numbers themselves.

Input
5
10
15
20
25
30
Output
Average: 20.0

2. Prime number. The method isPrime(int n) returns whether the number is prime (divisible only by 1 and by itself). For 7 it returns true, for 12 false.

3. Temperatures. The methods toFahrenheit(double c) and toCelsius(double f). F = C · 9 / 5 + 32. Read a temperature and a unit (C or F) and print the converted one.

Input
100
C
Output
100.0 C = 212.0 F

4. Calculator. The method calculate(double a, double b, char op) returns the result for +, -, * or /. The operation is chosen with if.

Input
10
5
+
Output
10.0 + 5.0 = 15.0

5. A triangle with a parameter. We promised it in the last lesson. The method printTriangle(int height) prints a right triangle of asterisks with height height. For 3:

Output
*
* *
* * *
More precisely, if you are curious

Watch out for 5 / 9 in the Celsius formula. Both numbers are whole numbers, so the division is integer division and the result is 0. Write (f - 32) * 5 / 9: then f - 32 is a double and the whole calculation is done with decimals.

Exercise

Methods for arrays

Each task is one method that gets an array (or a word) and returns a result. At the end, put them all together in one program.

  1. sum, sumEven and sumOdd: the sum of all the numbers, of the even ones and of the odd ones in the array.
  2. reverse: returns a new array with the numbers in reverse order.
  3. max and min: the largest and the smallest number.
  4. isPalindrome(String word): whether the word reads the same forward and backward.
  5. sumDiagonals and sumDiagonalsOnce: the sum along both diagonals of a square matrix, with the center element counted twice and once.
  6. All together: for the array { 1, 2, 3, 4, 5 }, the number 7 (with isPrime from the card above), the words "level" and "ABCDE" and the 3 × 3 matrix with the numbers from 1 to 9.
Output of task 6
Sum: 15, Even: 6, Odd: 9
Reversed: [5, 4, 3, 2, 1]
Max: 5, Min: 1
7 is prime: true
level: true, ABCDE: false
Sum with repeats: 30, Sum without repeats: 25

Test

Check yourself

1. In static double vat(double price), which one is the parameter?
2. A method changes its parameter. What happens to the variable you passed in the call?
3. What does return do?
4. A method is declared with the type double. What has to be true?
5. What does the line price = applyDiscount(price); do?

Made by Ivo Gergov as part of Evo Tech's campaign for accessible programming education ·