Java Methods
Method Declaration Syntax
A method is a reusable block of code that performs a specific task. The general syntax is:
accessModifier returnType methodName(parameterList) {
// method body
return value; // if returnType is not void
}
public class Methods {
// Static method — no object needed
public static int add(int a, int b) {
return a + b;
}
// Method overloading — same name, different parameters
public static double add(double a, double b) {
return a + b;
}
public static int add(int a, int b, int c) {
return a + b + c;
}
// void method — no return value
public static void greet(String name) {
System.out.println("Hello, " + name + "!");
}
public static void main(String[] args) {
System.out.println(add(3, 4)); // 7 (int version)
System.out.println(add(1.5, 2.5)); // 4.0 (double version)
System.out.println(add(1, 2, 3)); // 6 (3-param version)
greet("Alice"); // Hello, Alice!
}
}
Varargs (Variable Arguments)
Varargs let a method accept any number of arguments of the same type. The varargs parameter must be the last parameter and is treated as an array inside the method.
public class VarargsRecursion {
// Varargs — accepts 0 or more int arguments
public static int sum(int... numbers) {
int total = 0;
for (int n : numbers) total += n;
return total;
}
// Recursion — factorial
public static long factorial(int n) {
if (n <= 1) return 1; // base case
return n * factorial(n - 1); // recursive call
}
public static void main(String[] args) {
// Varargs
System.out.println(sum()); // 0
System.out.println(sum(5)); // 5
System.out.println(sum(1, 2, 3)); // 6
System.out.println(sum(1,2,3,4,5)); // 15
// Recursion
System.out.println(factorial(5)); // 120
System.out.println(factorial(10)); // 3628800
}
}
Static vs Instance Methods
| Feature | Static Method | Instance Method |
|---|---|---|
| Belongs to | The class | An object (instance) |
| Called with | ClassName.method() | object.method() |
| Can access instance fields? | No | Yes |
| Can access static fields? | Yes | Yes |
| Typical use | Utility/helper methods | Object behavior |
Ready to Level Up Your Skills?
Explore 500+ free tutorials across 20+ languages and frameworks.