Java Methods
Learn how to create reusable blocks of code with methods to make your programs more organized and efficient.
What is a Method?
A method is a block of code that performs a specific task. Think of it as a mini-program inside your main program. Instead of writing the same code multiple times, you write it once in a method and call it whenever needed.
Methods help you organize your code, make it reusable, and easier to maintain. They're also known as functions in other programming languages.
- Methods perform specific tasks or operations
- They make code reusable - write once, use many times
- Methods can accept input (parameters) and return output
- They help break large problems into smaller, manageable pieces
💡 Real-Life Analogy: A method is like a recipe. You write the steps once (define the method), and you can cook the dish anytime by following that recipe (calling the method).
Creating and Calling Methods
Let's see how to create a simple method and call it from the main method.
Example: Basic Method
public class MethodExample {
// Method definition
public static void greet() {
System.out.println("Hello, Welcome to Java!");
System.out.println("Methods make coding easier!");
}
public static void main(String[] args) {
// Calling the method
greet(); // First call
greet(); // Second call - reusing the same code
System.out.println("Method called successfully!");
}
}
Hello, Welcome to Java! Methods make coding easier! Hello, Welcome to Java! Methods make coding easier! Method called successfully!
Explanation:
public static void greet()- Defines a method named greetvoidmeans the method doesn't return any valuegreet();- Calls/executes the method- Method can be called multiple times without rewriting code
Method Syntax
Understanding the structure of a method helps you create them correctly.
Method Syntax:
accessModifier static returnType methodName(parameters) {
// method body
// code to execute
}
- Access Modifier: public, private, protected (controls visibility)
- static: Keyword that allows calling method without creating object
- Return Type: Data type of value returned (void if nothing returned)
- Method Name: Descriptive name following camelCase convention
- Parameters: Input values (optional, inside parentheses)
- Method Body: Code block inside curly braces
Methods with Parameters
Parameters allow you to pass data into methods, making them more flexible and reusable.
Example: Methods with Parameters
public class ParameterExample {
// Method with one parameter
public static void greetUser(String name) {
System.out.println("Hello, " + name + "!");
}
// Method with multiple parameters
public static void displayInfo(String name, int age) {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
}
public static void main(String[] args) {
// Calling method with argument
greetUser("Alice");
greetUser("Bob");
// Calling with multiple arguments
displayInfo("Charlie", 20);
displayInfo("Diana", 22);
}
}
Hello, Alice! Hello, Bob! Name: Charlie Age: 20 Name: Diana Age: 22
Explanation:
greetUser(String name)- Method accepts one parameter of type StringdisplayInfo(String name, int age)- Accepts two parametersgreetUser("Alice")- "Alice" is the argument passed to parameter name- Parameters act as variables inside the method
Methods with Return Values
Methods can return values back to the caller using the return statement.
Example: Returning Values from Methods
public class ReturnExample {
// Method returns an integer
public static int add(int a, int b) {
int sum = a + b;
return sum; // Returns the result
}
// Method returns a String
public static String getGrade(int marks) {
if (marks >= 90) {
return "A";
} else if (marks >= 80) {
return "B";
} else if (marks >= 70) {
return "C";
} else {
return "F";
}
}
public static void main(String[] args) {
// Store returned value in variable
int result = add(10, 20);
System.out.println("Sum: " + result);
// Use returned value directly
System.out.println("15 + 25 = " + add(15, 25));
// Get grade
String grade = getGrade(85);
System.out.println("Grade: " + grade);
}
}
Sum: 30 15 + 25 = 40 Grade: B
Explanation:
public static int add()- Return type is int, must return an integerreturn sum;- Sends the value back to the caller- Returned value can be stored in a variable or used directly
- Methods with return type other than void MUST have a return statement
Types of Methods
1. Method with No Parameters, No Return
Simple method that performs an action without taking input or returning output.
Example: public static void printMessage() { }
2. Method with Parameters, No Return
Takes input but doesn't return any value, just performs an action.
Example: public static void display(String text) { }
3. Method with No Parameters, with Return
Doesn't take input but returns a value to the caller.
Example: public static int getNumber() { return 42; }
4. Method with Parameters and Return
Takes input, processes it, and returns a result (most common type).
Example: public static int multiply(int a, int b) { return a * b; }
Method Overloading
Method overloading allows multiple methods with the same name but different parameters. Java distinguishes them by the number or type of parameters.
Example: Overloaded Methods
public class OverloadExample {
// Method 1: Two int parameters
public static int add(int a, int b) {
return a + b;
}
// Method 2: Three int parameters (overloaded)
public static int add(int a, int b, int c) {
return a + b + c;
}
// Method 3: Two double parameters (overloaded)
public static double add(double a, double b) {
return a + b;
}
public static void main(String[] args) {
System.out.println("Two integers: " + add(10, 20));
System.out.println("Three integers: " + add(10, 20, 30));
System.out.println("Two doubles: " + add(10.5, 20.5));
}
}
Two integers: 30 Three integers: 60 Two doubles: 31.0
Explanation:
- All three methods have the same name "add" but different parameters
- Java automatically calls the right method based on arguments passed
- Overloading differs by: number of parameters or data type of parameters
- Makes code more readable and flexible
Practical Example: Calculator
Let's create a simple calculator using methods to see how they work together in a real program.
Example: Calculator with Methods
public class Calculator {
// Addition method
public static int add(int a, int b) {
return a + b;
}
// Subtraction method
public static int subtract(int a, int b) {
return a - b;
}
// Multiplication method
public static int multiply(int a, int b) {
return a * b;
}
// Division method
public static double divide(int a, int b) {
if (b == 0) {
System.out.println("Error: Cannot divide by zero!");
return 0;
}
return (double) a / b;
}
// Display result method
public static void displayResult(String operation, double result) {
System.out.println(operation + ": " + result);
}
public static void main(String[] args) {
int x = 20, y = 5;
displayResult("Addition", add(x, y));
displayResult("Subtraction", subtract(x, y));
displayResult("Multiplication", multiply(x, y));
displayResult("Division", divide(x, y));
// Test division by zero
divide(10, 0);
}
}
Addition: 25.0 Subtraction: 15.0 Multiplication: 100.0 Division: 4.0 Error: Cannot divide by zero!
Explanation:
- Each mathematical operation has its own method for clarity
- Methods can be combined - one method calls another
- Error handling in divide method prevents crashes
- Code is organized, reusable, and easy to maintain
Recursion: Methods Calling Themselves
A method can call itself, which is known as recursion. This is useful for solving problems that can be broken into smaller similar problems.
Example: Factorial Using Recursion
public class RecursionExample {
// Recursive method to calculate factorial
public static int factorial(int n) {
// Base case: stop recursion
if (n == 0 || n == 1) {
return 1;
}
// Recursive case: method calls itself
return n * factorial(n - 1);
}
// Iterative version for comparison
public static int factorialIterative(int n) {
int result = 1;
for (int i = 1; i <= n; i++) {
result *= i;
}
return result;
}
public static void main(String[] args) {
int number = 5;
System.out.println("Factorial of " + number + " (Recursive): " + factorial(number));
System.out.println("Factorial of " + number + " (Iterative): " + factorialIterative(number));
// How recursion works: 5! = 5 * 4 * 3 * 2 * 1 = 120
}
}
Factorial of 5 (Recursive): 120 Factorial of 5 (Iterative): 120
Explanation:
factorial(5)callsfactorial(4), which callsfactorial(3), and so on- Base case
if (n == 0 || n == 1)stops the recursion - Each call waits for the next call to return before completing
- Recursion is elegant but can be memory-intensive for large numbers
Method Best Practices
- Descriptive Names: Use clear, action-oriented names like calculateTotal(), getUserInput()
- Single Purpose: Each method should do one thing and do it well
- Keep it Short: Methods should ideally be 10-20 lines of code
- Use Parameters: Pass data as parameters instead of using global variables
- Return Values: Use return statements to send results back instead of printing inside methods
- Comment Complex Logic: Add comments for methods with complicated operations
- Avoid Side Effects: Methods should not unexpectedly modify external variables
🎯 Golden Rule: If you're copying and pasting code, you probably need a method! Methods eliminate code duplication and make programs easier to maintain.
Common Method Mistakes to Avoid
1. Forgetting Return Statement
Methods with return type other than void must have a return statement.
Error: Missing return statement in non-void method
2. Wrong Number of Arguments
You must pass the exact number of arguments that match the method parameters.
Error: Calling method with too many or too few arguments
3. Incorrect Data Type
Arguments must match the data type of parameters defined in the method.
Error: Passing String when method expects int
4. Method Not Called
Defining a method doesn't execute it. You must call the method to run its code.
Error: Writing method but forgetting to call it in main()
Key Points to Remember
- Definition: Methods are reusable blocks of code that perform specific tasks
- Syntax: accessModifier static returnType methodName(parameters) { }
- Calling: Use methodName(arguments) to execute the method
- Parameters: Input values passed to methods (can have zero or more)
- Return: Use return keyword to send value back to caller
- void: Methods with void return type don't return any value
- Overloading: Multiple methods with same name but different parameters
- static: Allows calling method without creating an object (covered in OOP)
⚠️ Important: Methods must be called to execute. Simply defining a method doesn't run its code. Always call your methods from main() or from other methods!