Functions and Methods in Java

In Java, methods are similar to functions in other programming languages. They allow you to encapsulate logic into reusable blocks of code, making the program modular, readable, and maintainable. Java, being an object-oriented language, refers to these reusable blocks as methods because they are always associated with objects (either explicitly or implicitly).


What is a Method?

A method is a block of code that performs a specific task, grouped together so it can be reused multiple times in a program. Methods are used to perform operations, such as calculations, data manipulation, or interactions with objects.

Basic Structure of a Method:

returnType methodName(parameterList) {
    // Method body (logic)
    return value; // (optional, depending on return type)
}
  • returnType: The data type of the value returned by the method. If no value is returned, use void.
  • methodName: The name of the method (should follow naming conventions).
  • parameterList: A comma-separated list of input parameters (optional).
  • return value: If the method returns a value, it must match the return type.
Code Example

Explanation:

  • int add(int a, int b): This method takes two integers as input and returns their sum.
  • The method is called using the instance of the BasicMethodExample class (example.add(10, 20)).
  • The method's result is printed to the console (Sum: 30).