Methods
A method is a named block of code that does one job. Methods let you reuse logic, give it a clear name, and test it separately. (Other languages call them functions; in Java, every function lives inside a class, so it's called a method.)
Defining and calling methods
public class Main {
static String greet(String name) {
return "Hello, " + name + "!";
}
static double areaOfCircle(double radius) {
return Math.PI * radius * radius;
}
static void printLine(int length) { // void: returns nothing
System.out.println("-".repeat(length));
}
public static void main(String[] args) {
System.out.println(greet("Asha"));
printLine(20);
System.out.printf("Area: %.2f%n", areaOfCircle(3));
}
}Hello, Asha! -------------------- Area: 28.27
The parts of a method declaration:
static double areaOfCircle (double radius) { ... }
│ │ │ │
│ │ │ └── parameters: type and name of each input
│ │ └── name (camelCase, usually a verb)
│ └── return type (void if nothing is returned)
└── static: belongs to the class itself (more on this in the classes lesson)The compiler checks every call. Pass the wrong type, or forget to return a value, and the program won't compile:
public class Main {
static int square(int n) {
return n * n;
}
public static void main(String[] args) {
System.out.println(square("five"));
}
}Main.java:7: error: method square in class Main cannot be applied to given types;
System.out.println(square("five"));
^
required: int
found: String
reason: argument mismatch; String cannot be converted to int
1 error
error: compilation failedOverloading
Several methods can share a name if their parameters differ. Java picks the right one from the arguments:
public class Main {
static int add(int a, int b) { return a + b; }
static double add(double a, double b) { return a + b; }
static int add(int a, int b, int c) { return a + b + c; }
public static void main(String[] args) {
System.out.println(add(2, 3));
System.out.println(add(2.5, 3.1));
System.out.println(add(1, 2, 3));
}
}5 5.6 6
System.out.println itself is overloaded: there's a version for int, double, String and more.
Variable number of arguments
public class Main {
static double average(double... numbers) { // numbers is an array
double sum = 0;
for (double n : numbers) sum += n;
return numbers.length == 0 ? 0 : sum / numbers.length;
}
public static void main(String[] args) {
System.out.println(average(4, 8, 15, 16, 23, 42));
System.out.println(average(10));
System.out.println(average());
}
}18.0 10.0 0.0
Java passes arguments by value
A method receives a copy of each argument. Changing a primitive parameter never affects the caller's variable:
public class Main {
static void tryToChange(int x) {
x = 99;
}
static void addItem(StringBuilder text) {
text.append(" + extra"); // changes the object the copy points to
}
public static void main(String[] args) {
int number = 5;
tryToChange(number);
System.out.println(number);
StringBuilder sb = new StringBuilder("original");
addItem(sb);
System.out.println(sb);
}
}5 original + extra
For objects, the copy is a copy of the reference, so both point to the same object. The method can change the object's contents, but can't make the caller's variable point to a different object.
Scope
Variables exist only inside the block ({ }) where they're declared:
public class Main {
public static void main(String[] args) {
int total = 0;
for (int i = 1; i <= 3; i++) {
int squared = i * i; // only exists inside the loop
total += squared;
}
System.out.println(total);
System.out.println(squared);
}
}Main.java:9: error: cannot find symbol
System.out.println(squared);
^
symbol: variable squared
location: class Main
1 error
error: compilation failedRecursion
A method can call itself, as long as each call gets closer to a base case that stops it:
public class Main {
static long factorial(int n) {
if (n <= 1) return 1; // base case
return n * factorial(n - 1);
}
static int fibonacci(int n) {
return n < 2 ? n : fibonacci(n - 1) + fibonacci(n - 2);
}
public static void main(String[] args) {
System.out.println(factorial(10));
for (int i = 0; i < 10; i++) System.out.print(fibonacci(i) + " ");
System.out.println();
}
}3628800 0 1 1 2 3 5 8 13 21 34
Without a base case, the calls never end and the program crashes with a StackOverflowError.
Writing good methods
- One job per method, named with a verb:
calculateTotal,isValidEmail,sendInvoice. - Short: if it doesn't fit on a screen, split it.
- Return values rather than printing inside, so callers decide what to do with the result.
- Methods that answer yes/no usually start with
is,hasorcanand returnboolean.
public class Main {
static boolean isLeapYear(int year) {
return (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
}
static String describeYear(int year) {
return year + (isLeapYear(year) ? " is" : " is not") + " a leap year";
}
public static void main(String[] args) {
for (int y : new int[] {1900, 2000, 2024, 2025}) {
System.out.println(describeYear(y));
}
}
}1900 is not a leap year 2000 is a leap year 2024 is a leap year 2025 is not a leap year
Practice
- Write
static int max(int a, int b, int c)that returns the largest of three numbers. - Write
static boolean isPrime(int n)and print every prime below 50. - Write
static String reverse(String s)using a loop (or recursion), and test it on"Java".
1.What does void mean in a method declaration?
2.After calling tryToChange(number) (which sets its parameter to 99), what is number?
3.What is method overloading?