Java Methods¶
Table of Contents¶
- Introduction to Methods
- Understanding Method Structure
- Working with Methods
- Advanced Concepts
- Common Built-in Methods
- Best Practices
- Practice Questions
- Additional Resources
Introduction to Methods¶
What is a Method?¶
A method is like a recipe in a cookbook – it's a set of instructions that performs a specific task. Just as a recipe helps you create the same dish consistently, a method helps you execute the same code tasks reliably.
Real-World Analogy¶
Consider a coffee machine: - The machine is like a method - Inputs (water, coffee beans) are like parameters - Button press is like calling the method - Coffee output is like the return value
Why Use Methods?¶
- 
Code Organization - Like organizing a filing cabinet into folders
- Makes your program easier to understand
- Breaks complex problems into smaller pieces
 
- 
Reusability - Write once, use many times
- Like using the same coffee machine for different drinks
 
- 
Encapsulation - Hide complex operations behind simple interfaces
- Like using a microwave without knowing its internal workings
 
Understanding Method Structure¶
Basic Method Anatomy¶
public static returnType methodName(parameters) {
    // Method body
    // Code statements
    return result;
}
Components Explained¶
- 
Method Header - public static: modifiers- public: method can be called from any class
- static: method belongs to class, not object instances
 
- returnType: what kind of result the method produces
- methodName: descriptive name of the method
- parameters: required inputs
 
- 
Method Signature - Consists of: methodName+parameters list
- Used to uniquely identify a method
- Critical for method overloading
 
- Consists of: 
Example:
public static int calculateArea(int length, int width)
//             ^                ^       ^
//    Not part of |     These are part of signature
//    signature   |
// Signature is: calculateArea(int length, int width)
Multiple methods can have the same name but must have different signatures:
// Different signatures for calculateArea
calculateArea(int length, int width)           // rectangle
calculateArea(int radius)                      // circle
calculateArea(int base, int height, int side)  // triangle
// NOT a different signature (only return type differs)
double calculateArea(int length, int width)    // INVALID overload
- Method Body- Contains actual instructions
- Enclosed in curly braces { }
- May include a return statement
 
Example: Coffee Machine Method¶
public static String makeCoffee(String beanType, int waterAmount) {
    // Method that simulates making coffee
    String result = "";
    if (waterAmount < 100) {
        result = "Not enough water!";
    } else {
        result = "Your " + beanType + " coffee is ready!";
    }
    return result;
}
Working with Methods¶
Method Parameters¶
Parameters are like ingredients in a recipe:
- Must match in number (exact amount needed)
- Must match in type (right kind of ingredient)
- Must be in the correct order
Understanding Different Return Types¶
1. void Methods¶
Methods that don't return any value. They perform actions but don't produce a result.
// Example 1: Simple printing method
public static void printGreeting(String name) {
    System.out.println("Hello, " + name + "!");
}
// How to use:
printGreeting("Alice");  // Prints: Hello, Alice!
// Example 2: void method with multiple parameters
public static void displayUserInfo(String name, int age, String city) {
    System.out.println("Name: " + name);
    System.out.println("Age: " + age);
    System.out.println("City: " + city);
}
// How to use:
displayUserInfo("Bob", 25, "New York");
// COMMON MISTAKES with void methods:
int result = printGreeting("Alice");    // ERROR: void method cannot return value
return printGreeting("Alice");          // ERROR: cannot return void method
2. String Return Type¶
Methods that return text values.
// Example 1: Basic string concatenation
public static String createFullName(String firstName, String lastName) {
    return firstName + " " + lastName;
}
// How to use:
String fullName = createFullName("John", "Doe");
System.out.println(fullName);  // Prints: John Doe
// Example 2: String manipulation
public static String formatPhoneNumber(String phone) {
    if (phone.length() != 10) {
        return "Invalid number";
    }
    return "(" + phone.substring(0,3) + ") " + 
           phone.substring(3,6) + "-" + 
           phone.substring(6);
}
// How to use:
String formattedNumber = formatPhoneNumber("1234567890");
System.out.println(formattedNumber);  // Prints: (123) 456-7890
3. int Return Type¶
Methods that return integer values.
// Example 1: Basic calculation
public static int calculateArea(int length, int width) {
    return length * width;
}
// How to use:
int area = calculateArea(5, 3);
System.out.println("Area: " + area);  // Prints: Area: 15
// Example 2: More complex logic
public static int findLargest(int a, int b, int c) {
    if (a >= b && a >= c) {
        return a;
    } else if (b >= a && b >= c) {
        return b;
    } else {
        return c;
    }
}
// How to use:
int largest = findLargest(10, 5, 8);
System.out.println("Largest: " + largest);  // Prints: Largest: 10
4. double Return Type¶
Methods that return decimal values.
// Example 1: Calculate average
public static double calculateAverage(int[] numbers) {
    double sum = 0;
    for (int num : numbers) {
        sum += num;
    }
    return sum / numbers.length;
}
// How to use:
int[] scores = {85, 92, 78, 95, 88};
double average = calculateAverage(scores);
System.out.println("Average: " + average);  // Prints: Average: 87.6
// Example 2: Calculate discount
public static double applyDiscount(double price, double discountPercent) {
    return price - (price * discountPercent / 100);
}
// How to use:
double finalPrice = applyDiscount(100.00, 20);
System.out.println("Final price: $" + finalPrice);  // Prints: Final price: $80.0
Real-World Example Combining Different Types¶
Let's create a simple banking system example that uses various return types:
public class BankAccount {
    // void method - no return value
    public static void displayBalance(String accountName, double balance) {
        System.out.println("Account: " + accountName);
        System.out.println("Current balance: $" + balance);
    }
    // double method - returns calculated interest
    public static double calculateInterest(double balance, double rate) {
        return balance * (rate / 100);
    }
    // String method - returns account status
    public static String getAccountStatus(double balance) {
        if (balance < 0) {
            return "OVERDRAWN";
        } else if (balance < 1000) {
            return "NORMAL";
        } else {
            return "PREMIUM";
        }
    }
    // int method - returns number of years to reach goal
    public static int yearsToGoal(double currentBalance, double goal, double yearlyDeposit) {
        int years = 0;
        double balance = currentBalance;
        while (balance < goal) {
            balance += yearlyDeposit;
            years++;
        }
        return years;
    }
    // Example usage
    public static void main(String[] args) {
        String accountName = "John's Savings";
        double balance = 1500.00;
        // Using void method
        displayBalance(accountName, balance);
        // Using double method
        double interest = calculateInterest(balance, 2.5);
        System.out.println("Yearly interest: $" + interest);
        // Using String method
        String status = getAccountStatus(balance);
        System.out.println("Account status: " + status);
        // Using int method
        int years = yearsToGoal(balance, 5000, 1000);
        System.out.println("Years to reach goal: " + years);
    }
}
Key Points to Remember:¶
- 
Return Type Matching - The returned value must match the declared return type
- Type conversion may happen automatically for compatible types (e.g., int to double)
 
- 
Return Statement - Methods with a return type must have a return statement
- void methods don't need a return statement
- Return statement immediately exits the method
 
- 
Value Usage - Returned values must be used or stored
- void method calls must be statements
 
Return Values¶
- The result/output of the method
- Can only return ONE value
- Must match declared return type
- voidmeans no return value
Advanced Concepts¶
1. Method Overloading¶
Method overloading allows you to define multiple methods with the same name but different parameter lists.
Rules for Method Overloading:¶
- Different number of parameters
- Different parameter types
- Different parameter order
- Return type alone is NOT enough for overloading
public class CalculatorExample {
    // Basic overloading examples
    public static int add(int a, int b) {
        return a + b;
    }
    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;
    }
    // Real-world overloading example: Payment Processing
    public static double processPayment(double amount) {
        // Basic payment processing
        return amount;
    }
    public static double processPayment(double amount, String promoCode) {
        // Payment with promotion code
        if (promoCode.equals("SAVE10")) {
            return amount * 0.9; // 10% discount
        }
        return amount;
    }
    public static double processPayment(double amount, String promoCode, boolean isVIP) {
        // Payment with promotion and VIP status
        double price = amount;
        if (promoCode.equals("SAVE10")) {
            price *= 0.9; // 10% discount
        }
        if (isVIP) {
            price *= 0.95; // Additional 5% VIP discount
        }
        return price;
    }
}
2. Variable Scope¶
Variables have different levels of visibility based on where they are declared.
public class ScopeExample {
    // Class-level (field) scope
    private static int globalCounter = 0;
    public static void demonstrateScope() {
        // Method-level scope
        int localCounter = 0;
        // Block scope
        for (int i = 0; i < 5; i++) {  // 'i' only exists in this loop
            localCounter++;
            globalCounter++;
            System.out.println("Loop iteration: " + i);
            // New block scope
            {
                int blockVariable = 100;
                System.out.println("Block variable: " + blockVariable);
            }
            // blockVariable is not accessible here
        }
        System.out.println("Local counter: " + localCounter);
        System.out.println("Global counter: " + globalCounter);
    }
}
3. Parameter Passing¶
Java uses "pass-by-value" for all parameter passing. Understanding this is crucial for method behavior.
public class ParameterPassingExample {
    // Example with primitive types
    public static void modifyPrimitive(int x) {
        x = x + 1;  // This modification won't affect the original value
        System.out.println("Inside method: " + x);
    }
    // Example with object reference
    public static void modifyArray(int[] arr) {
        arr[0] = 100;  // This modification will affect the original array
        System.out.println("Inside method: " + Arrays.toString(arr));
    }
    public static void main(String[] args) {
        // Testing primitive parameter passing
        int number = 5;
        System.out.println("Before: " + number);
        modifyPrimitive(number);
        System.out.println("After: " + number);  // Still 5
        // Testing object reference parameter passing
        int[] numbers = {1, 2, 3};
        System.out.println("Before: " + Arrays.toString(numbers));
        modifyArray(numbers);
        System.out.println("After: " + Arrays.toString(numbers));  // First element is now 100
    }
}
Key Points to Remember:¶
- Method overloading is based on method signature, not return type
- Variables are only accessible within their scope
- Java uses pass-by-value for all parameters
Common Built-in Methods¶
1. Math Class Methods¶
The Math class provides a collection of static methods for performing common mathematical operations. All methods in Math class are static, so you don't need to create a Math object to use them.
Basic Mathematical Operations¶
public class MathExample {
    public static void demonstrateMathBasics() {
        // Absolute value
        System.out.println("Absolute value of -5: " + Math.abs(-5));    // 5
        System.out.println("Absolute value of 5.7: " + Math.abs(5.7));  // 5.7
        // Maximum and Minimum
        System.out.println("Maximum of 3.14 and 3.142: " + Math.max(3.14, 3.142));  // 3.142
        System.out.println("Minimum of 5 and 10: " + Math.min(5, 10));              // 5
        // Rounding Methods
        System.out.println("Round 3.7: " + Math.round(3.7));     // 4
        System.out.println("Round 3.2: " + Math.round(3.2));     // 3
        System.out.println("Ceiling 3.1: " + Math.ceil(3.1));    // 4.0
        System.out.println("Floor 3.9: " + Math.floor(3.9));     // 3.0
    }
}
Power and Root Operations¶
public class MathPowerExample {
    public static void demonstratePowerOperations() {
        // Power operations
        System.out.println("2 to the power 3: " + Math.pow(2, 3));        // 8.0
        System.out.println("Square root of 16: " + Math.sqrt(16));        // 4.0
        System.out.println("Cube root of 27: " + Math.cbrt(27));          // 3.0
        // Exponential and Logarithmic operations
        System.out.println("e to the power 2: " + Math.exp(2));           // 7.389...
        System.out.println("Natural log of 10: " + Math.log(10));         // 2.302...
        System.out.println("Log base 10 of 100: " + Math.log10(100));     // 2.0
    }
}
Trigonometric Operations¶
public class MathTrigExample {
    public static void demonstrateTrigOperations() {
        // Values in radians
        double angle = Math.PI / 4;  // 45 degrees
        System.out.println("Sine: " + Math.sin(angle));          // 0.7071...
        System.out.println("Cosine: " + Math.cos(angle));        // 0.7071...
        System.out.println("Tangent: " + Math.tan(angle));       // 1.0
        // Convert between degrees and radians
        double degrees = 45;
        double radians = Math.toRadians(degrees);
        System.out.println("45 degrees in radians: " + radians);
        System.out.println("π/4 radians in degrees: " + Math.toDegrees(Math.PI/4));
    }
}
Random Number Generation¶
public class MathRandomExample {
    public static void demonstrateRandomOperations() {
        // Random number between 0.0 (inclusive) and 1.0 (exclusive)
        System.out.println("Random number: " + Math.random());
        // Generate random integer between min and max (inclusive)
        public static int getRandomNumber(int min, int max) {
            return (int)(Math.random() * (max - min + 1)) + min;
        }
        // Examples
        System.out.println("Random number between 1 and 6: " + 
            getRandomNumber(1, 6));  // Simulating dice roll
        System.out.println("Random number between 1 and 100: " + 
            getRandomNumber(1, 100));
    }
}
2. String Methods¶
String class provides many methods for manipulating text. Unlike Math methods, these are instance methods and are called on String objects.
Basic String Operations¶
public class StringBasicExample {
    public static void demonstrateStringBasics() {
        String text = "Hello, World!";
        // Length and case operations
        System.out.println("Length: " + text.length());                    // 13
        System.out.println("Uppercase: " + text.toUpperCase());           // HELLO, WORLD!
        System.out.println("Lowercase: " + text.toLowerCase());           // hello, world!
        // Trimming whitespace
        String spacedText = "   Hello World   ";
        System.out.println("Trimmed: '" + spacedText.trim() + "'");      // 'Hello World'
        // Character extraction
        System.out.println("First char: " + text.charAt(0));             // H
        System.out.println("Last char: " + text.charAt(text.length()-1)); // !
    }
}
String Searching and Comparison¶
public class StringSearchExample {
    public static void demonstrateStringSearching() {
        String text = "The quick brown fox jumps over the lazy dog";
        // Finding substrings
        System.out.println("Index of 'quick': " + text.indexOf("quick"));     // 4
        System.out.println("Last index of 'the': " + text.lastIndexOf("the")); // 31
        // Checking content
        System.out.println("Starts with 'The': " + text.startsWith("The"));   // true
        System.out.println("Ends with 'dog': " + text.endsWith("dog"));       // true
        System.out.println("Contains 'fox': " + text.contains("fox"));        // true
        // Comparing strings
        String str1 = "Hello";
        String str2 = "hello";
        System.out.println("Equals: " + str1.equals(str2));                   // false
        System.out.println("Equals (ignore case): " + 
            str1.equalsIgnoreCase(str2));                                     // true
    }
}
String Manipulation¶
public class StringManipulationExample {
    public static void demonstrateStringManipulation() {
        String text = "Hello, World!";
        // Substring operations
        System.out.println("Substring(0,5): " + text.substring(0,5));    // Hello
        System.out.println("Substring(7): " + text.substring(7));        // World!
        // Replacing content
        System.out.println("Replace: " + text.replace("World", "Java")); // Hello, Java!
        System.out.println("Replace char: " + text.replace('l', 'w'));   // Hewwo, Worwd!
        // Splitting strings
        String csvText = "apple,banana,orange";
        String[] fruits = csvText.split(",");
        for (String fruit : fruits) {
            System.out.println("Fruit: " + fruit);
        }
        // Joining strings
        String joined = String.join(" | ", fruits);
        System.out.println("Joined: " + joined);  // apple | banana | orange
    }
}
Practical Examples¶
public class StringPracticalExamples {
    // Example 1: Password validation
    public static boolean isValidPassword(String password) {
        return password.length() >= 8 &&                  // Minimum length
               password.matches(".*[A-Z].*") &&           // At least one uppercase
               password.matches(".*[a-z].*") &&           // At least one lowercase
               password.matches(".*\\d.*");               // At least one digit
    }
    // Example 2: Email formatting
    public static String formatEmail(String email) {
        return email.trim().toLowerCase();
    }
    // Example 3: Name formatting
    public static String formatName(String name) {
        name = name.trim();
        if (name.isEmpty()) return "";
        // Capitalize first letter, lowercase rest
        return name.substring(0,1).toUpperCase() + 
               name.substring(1).toLowerCase();
    }
    public static void main(String[] args) {
        // Testing password validation
        System.out.println("Is valid password: " + 
            isValidPassword("Pass123word"));  // true
        // Testing email formatting
        System.out.println("Formatted email: " + 
            formatEmail("  User@EXAMPLE.com  "));  // user@example.com
        // Testing name formatting
        System.out.println("Formatted name: " + 
            formatName("jOHN"));  // John
    }
}
Key Points to Remember:¶
- 
Math Class: - All methods are static
- Returns precise mathematical calculations
- Commonly used for numerical computations
- Math.random() is useful for generating random numbers
 
- 
String Methods: - Strings are immutable - methods return new strings
- Case-sensitive by default
- Index positions start at 0
- Many methods for searching and manipulating text
 
Common Pitfalls to Avoid:¶
- Not storing the result of String methods (they return new strings)
- Using == instead of .equals() for String comparison
- Not handling null strings before calling methods
- Forgetting that Math.random() returns values < 1.0
- Not considering performance with large string manipulations
Would you like me to add more examples or explain any specific method in more detail?
Best Practices¶
- 
Naming Conventions - Use meaningful names (e.g., calculateTotalinstead ofcalc)
- Start with a verb (e.g., getName,calculateArea,printReport)
- Use camelCase notation
 
- Use meaningful names (e.g., 
- 
Method Design - Keep methods focused on one task
- Aim for methods that are short and clear
- Document your methods with comments
 
- 
Code Organization - Initialize variables before using them
- Use appropriate return types
- Handle errors appropriately
 
Practice Questions¶
Question 1¶
What will be the output of this code?
public static String greet(String name) {
    return "Hello, " + name + "!";
}
System.out.println(greet("John"));
Hello, John!
Question 2¶
Which method call is correct?
A)printAge("25");
B) printAge(25);
C) int result = printAge(25);
Answer: B) printAge(25);
Question 3¶
What's wrong with this method?
Answer: It's declared to return an int but doesn't have a return statement.Question 4¶
Which is a valid method overload?
A)public static int sum(int x, int y) { return x + y; }
B) public static int sum(int a, int b, int c) { return a + b + c; }
C) public static double sum(int a, int b) { return a + b; }
Answer: B) Adding a third parameter creates a valid overload