# Java Methods: Writing Reusable Code - Day 08

Methods in Java are a core concept that enables you to write modular, reusable, and clean code. They allow you to group a set of statements into a single unit, which can be executed when called. This makes your code more organized, readable, and efficient. This guide dives into Java methods, explaining their syntax, behavior, real-world scenarios, and practical examples to help you master this fundamental concept.

---

### Methods in Java: A Beginner’s Guide

A method is essentially a block of code designed to perform a specific task. Think of it as a recipe: once written, you can use it repeatedly without rewriting the instructions. Methods help you:

* **Encapsulate logic**: Make your code modular and easier to understand.
    
* **Promote reusability**: Write once and use multiple times.
    
* **Simplify maintenance**: Update logic in one place instead of multiple locations.
    

#### Syntax of a Method

The basic structure of a method in Java is as follows:

```java
returnType methodName(parameters) {
    // Method body
    // Code to execute
    return value; // Optional, depending on returnType
}
```

* `returnType`: Specifies the data type of the value the method returns (e.g., `int`, `String`, or `void` if nothing is returned).
    
* `methodName`: A unique identifier for the method.
    
* `parameters`: Variables passed into the method, enclosed in parentheses.
    
* `return`: A statement that specifies the value the method will return, if applicable.
    

#### Example: Adding Two Numbers

```java
public int addNumbers(int a, int b) {
    int sum = a + b;
    return sum;
}
```

Real-world Scenario: Imagine you’re building a calculator application. Instead of repeating the logic to add numbers in multiple places, you can create an `addNumbers` method. Whenever addition is needed, simply call this method.

---

### How Java Methods Work Behind the Scenes

When you call a method, the control of the program is transferred to the method’s body. After the method completes execution, control is returned to the caller along with any returned value (if applicable).

#### Steps:

1. **Define the Method**: Write the logic of the method using proper syntax.
    
2. **Call the Method**: Use the method name followed by parentheses to invoke it.
    
3. **Execute the Method**: The code inside the method runs and optionally returns a value.
    

#### Example: Multiply Two Numbers

```java
public class Example {
    public static void main(String[] args) {
        Example obj = new Example(); // Create an object
        int result = obj.multiplyNumbers(5, 10); // Call the method
        System.out.println("Result: " + result); // Print the result
    }

    public int multiplyNumbers(int a, int b) {
        return a * b;
    }
}
```

Output:

```plaintext
Result: 50
```

Real-world Scenario: This logic can be used in applications such as e-commerce platforms to calculate the total price when multiplying unit price by quantity.

---

### Components of a Method: Explained

Every method in Java consists of several key components. Let’s break them down:

1. **Method Header**: Includes the method’s name, parameters, and return type.
    
    * Example: `public int calculateSum(int a, int b)`
        
2. **Method Body**: Contains the logic to be executed.
    
    * Example: `{ return a + b; }`
        
3. **Method Parameters**: Variables passed into the method, used to process input.
    
    * Example: `(int a, int b)`
        
4. **Return Statement**: Returns a value to the caller, if applicable.
    
    * Example: `return a + b;`
        

#### Example: Calculating Circle Area

```java
public double calculateCircleArea(double radius) {
    double area = Math.PI * radius * radius;
    return area;
}
```

Real-world Scenario: This method can be used in a geometry application or an engineering tool where you need to compute the area of circles frequently.

---

### How to Call a Method in Java

To use a method, you need to call it by its name. Methods can be called from within the same class or another class.

#### Calling a Method in the Same Class

```java
public class Calculator {
    public static void main(String[] args) {
        Calculator calc = new Calculator();
        int sum = calc.add(5, 7);
        System.out.println("Sum: " + sum);
    }

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

#### Calling a Method in Another Class

```java
public class Main {
    public static void main(String[] args) {
        Helper helper = new Helper();
        helper.sayHello();
    }
}

class Helper {
    public void sayHello() {
        System.out.println("Hello, World!");
    }
}
```

Output:

```plaintext
Hello, World!
```

Real-world Scenario: For example, in a banking application, you might have separate classes for different operations like deposit, withdrawal, and balance inquiry. You can call methods from these classes based on the user’s action.

---

### Method Parameters: Passing Data to Methods

Method parameters allow you to pass data into methods for processing. Understanding how parameters work is essential for writing dynamic and flexible code.

#### Primitive Parameters (Pass-by-Value)

When passing primitives, Java creates a copy of the variable. Changes to the parameter inside the method do not affect the original variable.

```java
public void updateValue(int number) {
    number = number + 5;
    System.out.println("Inside method: " + number);
}

public static void main(String[] args) {
    int num = 10;
    updateValue(num);
    System.out.println("Outside method: " + num);
}
```

Output:

```plaintext
Inside method: 15
Outside method: 10
```

#### Reference Parameters (Pass-by-Reference)

When passing objects, changes made inside the method affect the original object.

```java
public void modifyArray(int[] arr) {
    arr[0] = 99;
}

public static void main(String[] args) {
    int[] numbers = {1, 2, 3};
    modifyArray(numbers);
    System.out.println(numbers[0]); // Output: 99
}
```

Real-world Scenario: Reference parameters are useful when working with large datasets or when you need to modify shared objects, like updating customer details in a database.

---

### Math Class Methods: Leveraging Built-In Functions

Java’s `Math` class provides a collection of static methods to perform mathematical operations efficiently. These methods eliminate the need to write complex algorithms from scratch.

#### Common Math Methods and Their Use Cases:

1. `Math.pow(base, exponent)`: Calculates the power of a number.
    
    * Use Case: Computing compound interest in a finance application.
        
2. `Math.sqrt(number)`: Returns the square root.
    
    * Use Case: Solving quadratic equations in a scientific calculator.
        
3. `Math.max(a, b)` and `Math.min(a, b)`: Finds the maximum and minimum values.
    
    * Use Case: Comparing scores in a gaming application.
        
4. `Math.abs(number)`: Returns the absolute value.
    
    * Use Case: Calculating distances or offsets in graphics programming.
        
5. `Math.random()`: Generates a random number between 0.0 and 1.0.
    
    * Use Case: Creating random dice rolls in a board game.
        

#### Example: Using Math Methods

```java
public class MathDemo {
    public static void main(String[] args) {
        double base = 2, exponent = 3;
        System.out.println("Power: " + Math.pow(base, exponent));

        double number = 16;
        System.out.println("Square Root: " + Math.sqrt(number));

        int a = 10, b = 20;
        System.out.println("Max: " + Math.max(a, b));
        System.out.println("Min: " + Math.min(a, b));

        int negative = -5;
        System.out.println("Absolute: " + Math.abs(negative));

        System.out.println("Random: " + Math.random());
    }
}
```

Output:

```plaintext
Power: 8.0
Square Root: 4.0
Max: 20
Min: 10
Absolute: 5
Random: 0.3456789
```

---

### Practice Problems

1. Write a method to calculate the factorial of a number.
    
2. Create a method that takes a string as input and returns it reversed.
    
3. Write a program with a method to check if a number is prime.
    
4. Implement a method to find the GCD (Greatest Common Divisor) of two numbers.
    
5. Create a method that generates a random number within a given range.
