In this lesson, we explore how methods can accept inputs (parameters) and return outputs (return values). This makes methods flexible and reusable for different data.
1. Method with Parameters
public class MethodParameters {
// method with parameters
static void greetUser(String name) {
System.out.println("Hello, " + name + "!");
}
public static void main(String[] args) {
greetUser("Alice");
greetUser("Bob");
}
}
Explanation: The method greetUser
takes a String
parameter and prints a personalized message. Each call can pass a different argument.
2. Method with Parameters and Return Value
public class MethodReturn {
// method that takes two numbers and returns sum
static int add(int a, int b) {
return a + b;
}
public static void main(String[] args) {
int result1 = add(5, 10);
int result2 = add(20, 30);
System.out.println("Sum1: " + result1);
System.out.println("Sum2: " + result2);
}
}
Explanation: The add
method receives two integers as input and returns their sum using the return
keyword. The result is stored in variables and printed.
3. Multiple Parameters Example
public class MethodMultipleParams {
static double calculateAverage(double a, double b, double c) {
return (a + b + c) / 3;
}
public static void main(String[] args) {
double avg = calculateAverage(10, 20, 30);
System.out.println("Average: " + avg);
}
}
Explanation: This method takes three numbers as input and returns their average.
Summary
Methods can take parameters to receive input values and use the return keyword to give back results. This allows you to build more powerful, reusable programs.