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).
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.public class BasicMethodExample {
// Method that adds two numbers
public int add(int a, int b) {
return a + b; // Returns the sum
}
public static void main(String[] args) {
BasicMethodExample example = new BasicMethodExample();
int sum = example.add(10, 20); // Calling the method
System.out.println("Sum: " + sum);
}
}
Explanation:
int add(int a, int b)
: This method takes two integers as input and returns their sum.BasicMethodExample
class (example.add(10, 20)
).Sum: 30
).