# Java Functions Explained
Here's a comprehensive guide to Java functions (methods), covering all essential aspects:
## 1. Basic Function Structure
```java
// Function definition
[access-modifier] [static] return-type functionName([parameters]) {
// Function body
return value; // if return-type is not void
}
// Example:
public static int addNumbers(int a, int b) {
return a + b;
}
```
## 2. Function Components
### Access Modifiers
- `public` - Accessible from any class
- `private` - Accessible only within its own class
- `protected` - Accessible within package and subclasses
- (default) - Accessible within package only
### Return Types
- Primitive types (`int`, `double`, `boolean`, etc.)
- Reference types (`String`, `Object`, custom classes)
- `void` - No return value
## 3. Function Examples
### Simple Function
```java
public void greet() {
System.out.println("Hello, World!");
}
```
### Function with Parameters
```java
public void greetByName(String name) {
System.out.println("Hello, " + name + "!");
}
```
### Function with Return Value
```java
public int square(int number) {
return number * number;
}
```
## 4. Function Overloading
```java
public class Calculator {
// Add two integers
public int add(int a, int b) {
return a + b;
}
// Add three integers
public int add(int a, int b, int c) {
return a + b + c;
}
// Add two doubles
public double add(double a, double b) {
return a + b;
}
}
```
## 5. Variable Arguments (Varargs)
```java
public int sum(int... numbers) {
int total = 0;
for (int num : numbers) {
total += num;
}
return total;
}
// Usage:
int result1 = sum(1, 2, 3); // 6
int result2 = sum(1, 2, 3, 4, 5); // 15
```
## 6. Recursive Functions
```java
public int factorial(int n) {
if (n == 0 || n == 1) {
return 1;
}
return n * factorial(n - 1);
}
```
## 7. Lambda Functions (Java 8+)
```java
// Functional interface
interface MathOperation {
int operate(int a, int b);
}
public class LambdaExample {
public static void main(String[] args) {
// Lambda function implementation
MathOperation addition = (a, b) -> a + b;
MathOperation subtraction = (a, b) -> a - b;
System.out.println(addition.operate(5, 3)); // 8
System.out.println(subtraction.operate(5, 3)); // 2
}
}
```
## 8. Method References
```java
import java.util.List;
import java.util.Arrays;
public class MethodReferenceExample {
public static void main(String[] args) {
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
// Static method reference
names.forEach(System.out::println);
// Instance method reference
names.forEach(String::toUpperCase);
}
}
```
## 9. Exception Handling in Functions
```java
public double divide(double dividend, double divisor) throws ArithmeticException {
if (divisor == 0) {
throw new ArithmeticException("Division by zero!");
}
return dividend / divisor;
}
// Usage with try-catch:
try {
double result = divide(10, 0);
} catch (ArithmeticException e) {
System.out.println("Error: " + e.getMessage());
}
```
## 10. Best Practices
1. **Naming**: Use verbs to describe what the function does (`calculateTotal`, `validateInput`)
2. **Single Responsibility**: Each function should do one thing well
3. **Parameter Count**: Keep parameters to a minimum (3-4 max)
4. **Documentation**: Use Javadoc for public methods
5. **Avoid Side Effects**: Functions should ideally only return values, not modify state
Would you like me to elaborate on any specific aspect of Java functions?
No comments:
Post a Comment