7.1 Creating and Invoking Methods:
- Methods are blocks of code that perform specific tasks. They allow you to break down your program into smaller, reusable pieces.
- Here's how you can create and invoke a method:
public class Greeting {
public static void greet() {
System.out.println("Hello, World!");
}
public static void main(String[] args) {
greet(); // Output: "Hello, World!"
}
}
7.2 Method Parameters and Return Types:
- Methods can take input parameters and return a value. Parameters are variables that allow you to pass values to the method, and return types specify the type of value the method will return.
public class Calculator {
public static int add(int num1, int num2) {
return num1 + num2;
}
public static void main(String[] args) {
int result = add(5, 3);
System.out.println("Result: " + result); // Output: "Result: 8"
}
}
7.3 Method Overloading:
- Method overloading allows you to have multiple methods with the same name but different parameters.
- This provides flexibility in accepting different types or numbers of arguments.
public class MathOperations {
public static int add(int num1, int num2) {
return num1 + num2;
}
public static double add(double num1, double num2) {
return num1 + num2;
}
public static void main(String[] args) {
int intResult = add(5, 3);
System.out.println("Integer Result: " + intResult); // Output: "Integer Result: 8"
double doubleResult = add(2.5, 3.7);
System.out.println("Double Result: " + doubleResult); // Output: "Double Result: 6.2"
}
}
7.4 Recursion:
- Recursion is a technique where a method calls itself to solve a problem. It's useful for solving problems that can be broken down into smaller, similar subproblems.
public class Factorial {
public static int factorial(int n) {
if (n == 0 || n == 1) {
return 1;
} else {
return n * factorial(n - 1);
}
}
public static void main(String[] args) {
int result = factorial(5);
System.out.println("Factorial: " + result); // Output: "Factorial: 120"
}
}