1. Declaring and Calling Methods
A method is defined once and can be called multiple times. A basic method includes:
- Return type (or
voidif nothing is returned) - Method name
- Optional parameters
- Method body
Try example:
public class MethodDemo {
static void greet() {
System.out.println("Welcome to VINAR TECH Tutorials");
}
public static void main(String[] args) {
greet(); // Calling the method
greet(); // You can call it multiple times
}
} 2. Parameters and Return Types
You can pass values to a method (known as parameters). Methods may also return a value.
Try example:
public class ParameterDemo {
static int add(int a, int b) {
return a + b; // Method returns an integer value
}
public static void main(String[] args) {
int result = add(10, 20);
System.out.println("Sum = " + result);
}
} Types of Methods
- Void methods: Perform an action but return nothing.
- Non-void methods: Return a computed value.
- Static methods: Called without creating an object.
- Instance methods: Require an object of the class.
3. Method Overloading
Method overloading means defining multiple methods with the same name but different parameter lists.
Try example:
public class OverloadDemo {
static int sum(int a, int b) {
return a + b;
}
static double sum(double a, double b) {
return a + b;
}
public static void main(String[] args) {
System.out.println(sum(5, 10)); // int version
System.out.println(sum(5.5, 2.7)); // double version
}
} 4. Returning Objects from Methods
Methods can return not only primitive values but also objects.
Try example:
class User {
String name;
User(String name) {
this.name = name;
}
}
public class ObjectReturnDemo {
static User createUser(String name) {
return new User(name);
}
public static void main(String[] args) {
User u = createUser("VINAR TECH");
System.out.println("Created User: " + u.name);
}
} 5. Recursion
Recursion occurs when a method calls itself. Every recursive method must have:
- A base condition (stopping point)
- A recursive step (calls itself with new input)
Try example:
public class RecursionDemo {
static int factorial(int n) {
if (n == 0) {
return 1; // Base case
}
return n * factorial(n - 1); // Recursive call
}
public static void main(String[] args) {
System.out.println("Factorial of 5 = " + factorial(5));
}
} 6. Best Practices for Methods
- Use meaningful method names (e.g.,
calculateTotal()) - Keep methods short and focused on a single task
- Organize related methods inside proper classes
- Use method overloading to avoid confusing method names
- Use recursion only when it simplifies logic