Methods in Java

A method in Java is a block of code that performs a specific task. It is a fundamental part of Java's programming structure and enables code reusability and organization.

Key Points on Methods:

Syntax of a Method:

Syntax Example

returnType methodName(parameterType parameterName) {
    // Code to execute
    return value; // Optional
}

Example of a Method in Java:

This example demonstrates a simple method that adds two numbers and returns the result.

Code Example: Method Definition

public class Calculator {
    // Method to add two numbers
    public int add(int a, int b) {
        return a + b; // Return the sum
    }
}

Using the Method:

This example shows how to create an object of the Calculator class and call the add method.

Code Example: Method Usage

public class Main {
    public static void main(String[] args) {
        // Creating an object of Calculator
        Calculator calculator = new Calculator();
        
        // Calling the add method
        int sum = calculator.add(5, 10);
        
        // Displaying the result
        System.out.println("Sum: " + sum);
    }
}

Output

Sum: 15

Detailed Explanation:

Mastering methods is essential for effective programming in Java, as they promote code reusability and better organization of code.