Card 01/ 10
Java Methods: Declaring and Calling a Method
Four lines that work out VAT, copied into three places, and a rounding fix that reaches only one.
A method is a block of code with a name, which other code runs by calling that name. You declare it once, with the type of value it hands back and the values it needs, and every caller shares the one copy, so a fix made in the method reaches all of them.
The same four lines that work out VAT appear in three places in your file. You fix a rounding mistake in one of them and ship the other two unfixed. A method is those lines given a name, written once, and called from wherever they were. The amount is held as a whole number of pence, as money should be:
long vatOn(long pence) {
return pence * 20 / 100;
}
long lineVat = vatOn(1999);
long deliveryVat = vatOn(499);Three things are happening in that declaration. long says what the method hands back. vatOn is the name callers use. (long pence) says what it needs before it can do anything, and the name in there is used only inside the body. return ends the method and hands the value back to the caller.
Calling it is the name followed by the values it needs in brackets, as in vatOn(1999). The call is an expression, so its result can be stored, printed or passed straight into another call.
What changes is not how much code exists; it is how many places have to be right. A method is a name for a decision about where correctness lives: the rounding fix now happens in one place, and every caller gets it without being touched.
← → move through sections and cards