What Is a Method in Java?
A method is a named, reusable block of code inside a class. It performs a task, optionally accepts input parameters, and optionally returns a value. Methods are how Java objects expose their behaviour.
Anatomy of a method
public int add(int a, int b) {
return a + b;
}
public— access modifier (who can call it)int— return type (what it gives back; usevoidif nothing is returned)add— method name(int a, int b)— parameter list- Body between
{ }
Instance methods
Instance methods operate on a specific object's state:
public class BankAccount {
private double balance;
public void deposit(double amount) {
balance += amount;
}
public double getBalance() {
return balance;
}
}
BankAccount acct = new BankAccount();
acct.deposit(100.0);
System.out.println(acct.getBalance()); // 100.0
Static methods
Static methods belong to the class, not an instance. You call them without creating an object:
public class MathUtils {
public static double circleArea(double radius) {
return Math.PI * radius * radius;
}
}
double area = MathUtils.circleArea(5.0);
Void methods
Methods that perform an action but return nothing use void:
public void printReceipt(String item, double price) {
System.out.printf("%-20s $%.2f%n", item, price);
}
Method overloading
Multiple methods can share the same name if their parameter lists differ (different types or count):
public int max(int a, int b) { return a > b ? a : b; }
public double max(double a, double b) { return a > b ? a : b; }
public int max(int a, int b, int c) { return max(max(a, b), c); }
max(3, 5); // calls int version
max(3.0, 5.0); // calls double version
max(1, 2, 3); // calls 3-arg version
Method naming conventions
- Use camelCase:
calculateTax,getUserById,isValid. - Start with a verb for non-getter/setter methods:
process,send,calculate. - Getter methods start with
get(orisfor booleans):getName(),isEnabled().
Return type and returning values
public String greet(String name) {
if (name == null || name.isBlank()) {
return "Hello, stranger!"; // early return
}
return "Hello, " + name + "!";
}
return exits the method immediately and gives back a value. A void method can use a bare return; to exit early.