A method in Java is a block of code that performs a specific task. Methods help us reuse code, reduce repetition, and make programs easier to understand.
Basic Syntax
returnType methodName(parameters) {
// code
}
Example
class Main {
static void greet() {
System.out.println("Hello Java!");
}
public static void main(String[] args) {
greet();
}
}
Output:
Hello Java!
Method with Parameters
A method can accept values called parameters.
static int add(int a, int b) {
return a + b;
}
We can call it like this:
int result = add(10, 20);
System.out.println(result);
Output:
30
Here, a and b are parameters, while 10 and 20 are arguments.
Types of Methods
Methods can be commonly classified as:
- No parameter and no return value
- Parameter but no return value
- No parameter but return value
- Parameter and return value
Method Overloading
Java also supports method overloading, where multiple methods have the same name but different parameters.
static int add(int a, int b) {
return a + b;
}
static int add(int a, int b, int c) {
return a + b + c;
}
Why Use Methods?
- Code reusability
- Less code duplication
- Better readability
- Easier debugging
- Breaks a large program into smaller tasks
Conclusion
Methods are one of the most important concepts in Java. By using methods, we can write clean, reusable, and organized code. Understanding parameters, return values, and method overloading is especially important for Java programming and interviews.
Top comments (0)