Function

In Java, functions are known as methods. A method is a block of code that performs a specific task and can be called from other parts of the program. Methods are used for code reusability and organization. Here's how you define and use methods in Java:

Method Declaration:

In Java, a method is declared within a class. The basic syntax of a method declaration looks like this:

access_modifier return_type method_name(parameter_list) {
    // Method body
    // Code to be executed
    return value; // Return statement (if the method returns a value)
}
  • access_modifier: Specifies the visibility of the method (public, private, protected, or package-private).

  • return_type: Specifies the data type of the value the method returns. Use void if the method doesn't return any value.

  • method_name: Specifies the name of the method.

  • parameter_list: Specifies the parameters the method accepts (if any).

  • return value: Specifies the value to be returned by the method (if applicable).

Example of a Method:

public class Example {

    // Method that takes two integers as parameters and returns their sum
    public int addNumbers(int a, int b) {
        int sum = a + b;
        return sum;
    }

    public static void main(String[] args) {
        Example example = new Example();
        int result = example.addNumbers(5, 10);
        System.out.println("Sum: " + result);
    }
}

Explanation:

  1. public int addNumbers(int a, int b) { ... }: This line declares a method named addNumbers with two integer parameters (a and b). The method returns an integer (int). Inside the method, the two parameters are added, and the sum is stored in the sum variable. The method then returns the sum.

  2. Example example = new Example();: Creates an instance of the Example class.

  3. int result = example.addNumbers(5, 10);: Calls the addNumbers method of the example object with the arguments 5 and 10. The returned sum (15 in this case) is stored in the result variable.

  4. System.out.println("Sum: " + result);: Prints the result, which is 15, to the console.

When you run this Java program, it will output:

Sum: 15

This output shows the result of calling the addNumbers method with the arguments 5 and 10. The method calculated the sum and returned the value 15, which was then printed in the main method.

Last updated