Monday, July 21, 2025

Java Learn

# **Java Functions (Methods) - Complete Guide**

Functions (also called methods in Java) are blocks of code that perform specific tasks and can be reused throughout your program. Let's explore Java functions in depth.

## **1. Function Basics**

### **Function Structure**
```java
accessModifier returnType methodName(parameters) {
    // method body
    return value; // if return type is not void
}
```

### **Simple Example**
```java
public class Main {
    // Function definition
    public static void greet() {
        System.out.println("Hello, World!");
    }

    public static void main(String[] args) {
        greet(); // Function call
    }
}
```

## **2. Function Components**

### **Return Types**
- `void` - No return value
- Primitive types (`int`, `double`, etc.)
- Reference types (`String`, arrays, objects)

```java
public static int add(int a, int b) {
    return a + b;
}

public static String getMessage() {
    return "Welcome to Java!";
}
```

### **Parameters**
```java
public static void printDetails(String name, int age) {
    System.out.println(name + " is " + age + " years old");
}
```

## **3. Types of Functions**

### **1. No Parameters, No Return**
```java
public static void sayHello() {
    System.out.println("Hello!");
}
```

### **2. With Parameters, No Return**
```java
public static void printSum(int a, int b) {
    System.out.println("Sum: " + (a + b));
}
```

### **3. With Return, No Parameters**
```java
public static double getPi() {
    return 3.14159;
}
```

### **4. With Parameters and Return**
```java
public static int multiply(int x, int y) {
    return x * y;
}
```

## **4. Function Overloading**

Multiple functions can have the same name but different parameters.

```java
public class Calculator {
    // Add two integers
    public static int add(int a, int b) {
        return a + b;
    }
    
    // Add three integers
    public static int add(int a, int b, int c) {
        return a + b + c;
    }
    
    // Add two doubles
    public static double add(double a, double b) {
        return a + b;
    }
}
```

## **5. Variable Scope in Functions**

- **Local Variables**: Exist only within the function
- **Parameters**: Act as local variables

```java
public static void calculate() {
    int x = 10; // Local variable
    System.out.println(x);
}
// x is not accessible here
```

## **6. Recursion**

A function that calls itself.

```java
public static int factorial(int n) {
    if (n == 0 || n == 1) {
        return 1;
    }
    return n * factorial(n - 1);
}
```

## **7. Best Practices**

1. **Single Responsibility**: Each function should do one thing
2. **Descriptive Names**: Use verbs (`calculateArea`, `printReport`)
3. **Limit Parameters**: 3-4 parameters max (use objects if needed)
4. **Avoid Side Effects**: Functions should only do what their name suggests
5. **Documentation**: Use comments for complex functions

```java
/**
 * Calculates the area of a rectangle
 * @param length - the length of the rectangle
 * @param width - the width of the rectangle
 * @return area of the rectangle
 */
public static double calculateRectangleArea(double length, double width) {
    return length * width;
}
```

## **8. Common Function Examples**

### **Check Even/Odd**
```java
public static boolean isEven(int number) {
    return number % 2 == 0;
}
```

### **Find Maximum**
```java
public static int findMax(int a, int b) {
    return (a > b) ? a : b;
}
```

### **Reverse String**
```java
public static String reverseString(String str) {
    return new StringBuilder(str).reverse().toString();
}
```

## **9. Advanced Concepts**

### **Varargs (Variable Arguments)**
```java
public static int sum(int... numbers) {
    int total = 0;
    for (int num : numbers) {
        total += num;
    }
    return total;
}
// Usage: sum(1, 2, 3) or sum(1, 2, 3, 4, 5)
```

### **Lambda Functions (Java 8+)**
```java
interface MathOperation {
    int operate(int a, int b);
}

public static void main(String[] args) {
    MathOperation addition = (a, b) -> a + b;
    System.out.println(addition.operate(5, 3)); // 8
}
```

## **10. Exercises to Practice**

1. Write a function to check if a number is prime
2. Create a function to calculate Fibonacci sequence
3. Write a function that converts Celsius to Fahrenheit
4. Implement a function to find the GCD of two numbers
5. Create a recursive function to calculate power of a number

Mastering functions is crucial for writing clean, modular Java code. Practice creating different types of functions to become comfortable with their usage.

No comments: