Defining and Calling Methods
Methods are reusable blocks of code that perform a specific task. They can accept parameters and return values.
Example
public class Calculator {
// Method with return value
static int add(int a, int b) {
return a + b;
}
// Method with no return value (void)
static void greet(String name) {
System.out.println("Hello, " + name + "!");
}
// Method with default behavior
static double calculateTax(double amount, double rate) {
return amount * rate;
}
public static void main(String[] args) {
int sum = add(5, 3); // 8
greet("Alice"); // "Hello, Alice!"
double tax = calculateTax(100, 0.08); // 8.0
}
} Method Overloading and Varargs
Method overloading lets you define multiple methods with the same name but different parameters. Varargs accept a variable number of arguments.
Example
// Method overloading — same name, different parameters
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;
}
// Varargs — variable number of arguments
static int sum(int... numbers) {
int total = 0;
for (int n : numbers) {
total += n;
}
return total;
}
sum(1, 2); // 3
sum(1, 2, 3, 4); // 10 