java


1. Introduction

In Java, **methods** are blocks of code designed to perform a specific task.
Instead of writing the same code multiple times, we can place it inside a method and **reuse it whenever needed**.

Methods improve **code reusability, readability, and maintainability**, making programs more organized. 

Introduction java methods

In Java, methods are blocks of code designed to perform a specific task. Instead of writing the same code multiple times, we can place it inside a method and reuse it whenever needed. Methods improve code reusability, readability, and maintainability, making programs more organized. Types of Methods in Java Predefined Methods → Already available in Java (e.g., Math.max(), System.out.println()). User-defined Methods → Created by the programmer.

public class MyClass {

    public void greet() {
        System.out.println("Hello, Welcome to Java!");
    }

    public static void main(String[] args) {
        MyClass obj = new MyClass(); // create object
        obj.greet(); // method call
    }
} 

Method Parameters

Parameters are variables passed into a method so it can work with different data.

Example with Parameters:
public class Calculator {

    // Method with parameters
    public void addNumbers(int a, int b) {
        System.out.println("Sum: " + (a + b));
    }

    public static void main(String[] args) {
        Calculator calc = new Calculator();
        calc.addNumbers(10, 20); // passing arguments
    }
} 

Return Values from Methods

If a method returns a value, its return type cannot be void. The return statement sends the result back to the caller.

public class Calculator {

    // Method with return type
    public int multiply(int x, int y) {
        return x * y;
    }

    public static void main(String[] args) {
        Calculator calc = new Calculator();
        int result = calc.multiply(5, 4);
        System.out.println("Product: " + result);
    }
}