A method is a named block of code inside a class. Its signature declares the return type, name and parameter types: static double percentage(int score, int outOf). void means it returns nothing.
Overloading lets several methods share a name with different parameter lists — average(int[] values) and average(double[] values). Varargs (int... values) accept any number of arguments.
Java always passes arguments by value: a method gets a copy of a primitive, so changing it inside has no effect outside. For objects and arrays, the copy is a reference to the same object, so the method can change the object's contents.
public class Methods {
static int percentage(int score, int outOf) {
return (int) Math.round(score * 100.0 / outOf);
}
static int percentage(int score) { // overload with a default "out of"
return percentage(score, 100);
}
static double average(int... values) { // varargs
if (values.length == 0) return 0;
int total = 0;
for (int v : values) total += v;
return (double) total / values.length;
}
static String greet(String name, String title) {
return title == null ? "Hello, " + name : "Hello, " + title + " " + name;
}
static void tryToChange(int number, int[] numbers) {
number = 99; // changes the local copy only
numbers[0] = 99; // changes the shared array
}
public static void main(String[] args) {
System.out.println(percentage(42, 50)); // 84
System.out.println(percentage(73)); // 73
System.out.println(average(78, 64, 91)); // 77.66666666666667
System.out.println(greet("Amina", null));
System.out.println(greet("Juma", "Mr."));
int n = 1;
int[] arr = {1, 2, 3};
tryToChange(n, arr);
System.out.println(n + " " + arr[0]); // 1 99
}
}Key points
- Declare parameter and return types;
voidreturns nothing. - Overloading and varargs give flexible, readable method calls.
- Arguments are passed by value — object contents can still be changed through a reference.
Exercise
Write areaOfRectangle(double w, double h), areaOfCircle(double r) and an overloaded describe(double area) / describe(double area, String units) that returns "Area: 12.00 sq cm".
Show solution
Try the exercise yourself first — then compare your approach with this one.
Two describe methods share a name but take different parameters (overloading). The one-argument version calls the two-argument version with "cm", so the formatting lives in one place.
public class Areas {
static double areaOfRectangle(double width, double height) {
return width * height;
}
static double areaOfCircle(double radius) {
return Math.PI * radius * radius;
}
static String describe(double area, String units) {
return String.format("Area: %.2f sq %s", area, units);
}
static String describe(double area) {
return describe(area, "cm");
}
public static void main(String[] args) {
System.out.println(describe(areaOfRectangle(3, 4))); // Area: 12.00 sq cm
System.out.println(describe(areaOfCircle(2), "m")); // Area: 12.57 sq m
}
}