In this tutorial
As your programs grow, copying the same ten lines in three places becomes a maintenance nightmare. Methods let you give a block of code a name, run it whenever you need it, and change it in one place.
In this tutorial you will learn how to declare and call methods, pass data in and get results out, overload methods, and avoid the classic “why didn’t my variable change?” confusion.
Anatomy of a method
public static double applyDiscount(double price, double percent) {
return price - (price * percent / 100);
}
Reading it from left to right:
public: the access modifier. Who can call this method.static: belongs to the class rather than an object. More on this below.double: the return type. Usevoidif the method returns nothing.applyDiscount: the name, written in camelCase and ideally starting with a verb.(double price, double percent): the parameters, the inputs the method expects.- The body between
{ }, ending withreturnto send a value back.
The name plus parameter types form the method’s signature.
Calling a method
public class Shop {
static double applyDiscount(double price, double percent) {
return price - (price * percent / 100);
}
static void printReceipt(String item, double amount) {
System.out.printf("%-10s NGN %,.2f%n", item, amount);
}
public static void main(String[] args) {
double shoes = applyDiscount(25_000, 20);
double bag = applyDiscount(18_500, 10);
printReceipt("Shoes", shoes);
printReceipt("Bag", bag);
printReceipt("Total", shoes + bag);
}
}
Output:
Shoes NGN 20,000.00
Bag NGN 16,650.00
Total NGN 36,650.00
The values you pass when calling (25_000, 20) are called arguments. They are matched to parameters by position, and their types must be compatible.
Return values
A method with a non-void return type must return a value on every path:
static String classify(int temperature) {
if (temperature > 30) {
return "hot";
} else if (temperature > 18) {
return "warm";
}
return "cold"; // without this line the code would not compile
}
return also ends the method immediately, which is handy for guard clauses:
static double safeDivide(double a, double b) {
if (b == 0) {
return 0;
}
return a / b;
}
A void method can use a bare return; to exit early.
Java is always pass-by-value
This is the concept that confuses most beginners, and it is a favourite interview question.
When you call a method, Java copies each argument into the parameter. For primitives, the value itself is copied, so the method cannot change the caller’s variable:
static void addBonus(int salary) {
salary += 50_000;
}
int salary = 300_000;
addBonus(salary);
System.out.println(salary); // still 300000
For objects, the reference is copied. Both the caller and the method now point at the same object, so the method can change the object’s contents, but it cannot make the caller’s variable point to a different object:
import java.util.ArrayList;
import java.util.List;
public class PassByValue {
static void addItem(List<String> cart) {
cart.add("Rice"); // changes the shared list: visible to caller
}
static void replaceCart(List<String> cart) {
cart = new ArrayList<>(); // only changes the local copy of the reference
cart.add("Beans");
}
public static void main(String[] args) {
List<String> cart = new ArrayList<>();
addItem(cart);
replaceCart(cart);
System.out.println(cart); // [Rice]
}
}
If a method needs to produce a new value, return it instead of trying to modify the argument.
Method overloading
You can have several methods with the same name as long as their parameter lists differ in number or type. Java picks the right one at compile time:
public class AreaCalculator {
static double area(double radius) {
return Math.PI * radius * radius;
}
static double area(double width, double height) {
return width * height;
}
static double area(double a, double b, double c) {
double s = (a + b + c) / 2; // Heron's formula
return Math.sqrt(s * (s - a) * (s - b) * (s - c));
}
public static void main(String[] args) {
System.out.printf("Circle: %.2f%n", area(3));
System.out.printf("Rectangle: %.2f%n", area(4, 5));
System.out.printf("Triangle: %.2f%n", area(3, 4, 5));
}
}
The return type alone is not enough to overload. int total() and double total() in the same class will not compile.
Variable arguments (varargs)
When a method should accept any number of values, use ...:
static int sum(int... numbers) {
int total = 0;
for (int n : numbers) {
total += n;
}
return total;
}
sum(); // 0
sum(4); // 4
sum(1, 2, 3, 4); // 10
Inside the method, numbers is just an array. A varargs parameter must be the last one in the list.
static versus instance methods
A static method belongs to the class. You call it with the class name (Math.max(3, 7)) and it cannot use the object’s fields directly.
An instance method belongs to an object and can use that object’s fields:
public class BankAccount {
private double balance;
public void deposit(double amount) { // instance method
if (amount <= 0) {
throw new IllegalArgumentException("Amount must be positive");
}
balance += amount;
}
public double getBalance() {
return balance;
}
public static void main(String[] args) {
BankAccount account = new BankAccount();
account.deposit(5_000);
System.out.println(account.getBalance()); // 5000.0
}
}
Use static for pure helper functions that only depend on their parameters. Use instance methods for behaviour that belongs to an object. See classes and objects in Java for more.
Writing good methods
- Do one thing. If you need “and” to describe it, consider splitting it.
- Keep them short. If a method does not fit on your screen, it is probably doing too much.
- Name them well.
calculateShippingFeebeatscalcordoStuff. - Limit parameters. More than three or four usually means you should pass an object instead.
- Avoid hidden side effects. A method called
getTotalshould not also send an email.
Practice
- Write
isPrime(int n)that returnstrueifnis prime. - Overload
maxto work with twoints, threeints and twodoubles. - Write
average(double... values)and make it return0when called with no arguments.
Summary
- A method has a return type, name, parameters and a body.
- Arguments are always passed by value; for objects, that value is a reference.
- Overloading lets one name handle different parameter lists.
- Varargs (
int...) accept any number of arguments. - Use
staticfor helpers and instance methods for object behaviour.
Next: working with Strings in Java.