What is a Method in Java?
A method in Java is a block of code that performs a specific task. Methods help to reuse code — you write it once and call it whenever needed.
Syntax of a Method:
returnType methodName(parameter1, parameter2, ...) {
// code to be executed
return value;
}
Types of Methods:
- Predefined Methods – Already available in Java (like
System.out.println()
).
- User-defined Methods – Created by the programmer to perform specific tasks.
Example 1: A Simple Method (No Parameters, No Return)
public class HelloWorld {
// method definition
public static void greet() {
System.out.println("Hello, welcome to Java!");
}
public static void main(String[] args) {
greet(); // method call
}
}
Output:
Hello, welcome to Java!
Example 2: Method with Parameters
public class Calculator {
// method with parameters
public static void add(int a, int b) {
int sum = a + b;
System.out.println("Sum: " + sum);
}
public static void main(String[] args) {
add(5, 10); // method call with arguments
}
}
Output:
Sum: 15
Example 3: Method with Return Value
public class Multiply {
// method returns an int
public static int multiply(int x, int y) {
return x * y;
}
public static void main(String[] args) {
int result = multiply(4, 5);
System.out.println("Result: " + result);
}
}
Output:
Result: 20
Example 4: Method Overloading (Same name, different parameters)
public class OverloadExample {
public static int square(int x) {
return x * x;
}
public static double square(double x) {
return x * x;
}
public static void main(String[] args) {
System.out.println("Square of 5: " + square(5));
System.out.println("Square of 2.5: " + square(2.5));
}
}
Output:
Square of 5: 25
Square of 2.5: 6.25
Why Use Methods?
- Reusability – Avoid repeating code
- Modularity – Break big problems into smaller parts
- Maintainability – Easy to update or debug
- Readability – Improves structure and clarity