Methods in Java
Learn how to organize code into reusable pieces
Think of methods like recipes! Just like a recipe tells you how to make a specific dish (and you can use that recipe many times), a method is a set of instructions that does a specific job. Instead of writing the same code over and over, you write it once in a method and use it whenever you need it!
What is a Method?
A method is a block of code that performs a specific task. It's like a mini-program inside your program!
// A simple method examplepublic int calculateSum(int a, int b) { int sum = a + b; return sum;}// Using the methodint result = calculateSum(5, 3); // result is 8System.out.println(result); // Prints: 8// You can use it many times!int x = calculateSum(10, 20); // x is 30int y = calculateSum(100, 50); // y is 150🔍 Anatomy of a Method
Let's break down what makes up a method:
// ① ② ③ ④// ↓ ↓ ↓ ↓public int greetUser (String name) { // ⑤ Method body System.out.println("Hello, " + name + "!"); return 1; // Success code}Access Modifier
public, private, protectedWho can use this method
Return Type
int, String, voidWhat kind of data it returns (void = nothing)
Method Name
calculateSum, printMessageWhat the method is called
Parameters
(int a, int b)Data the method needs to work (can be empty)
Method Body
{ /* code here */ }The actual code that runs
🎯 Types of Methods
Different kinds of methods for different purposes:
Void Methods
Do something but don't return anything
public void printHello() { }💡 Like telling someone 'Close the door' - they do it but don't give you anything back
Return Methods
Calculate something and return the result
public int add(int a, int b) { return a + b; }💡 Like asking 'What's 2+2?' - you get an answer back
Static Methods
Belong to the class, not objects
public static void main(String[] args) { }💡 Like a shared tool anyone can use without owning it
Instance Methods
Belong to objects, need an object to call
public void setName(String name) { }💡 Like a person's ability - each person has their own
📝 Code Examples: Method Types
public class MethodTypesDemo { // VOID METHOD - Does something, returns nothing public void printWelcome() { System.out.println("Welcome to Java!"); System.out.println("Let's learn methods!"); // No return statement needed } // RETURN METHOD - Returns a value public int multiply(int x, int y) { int result = x * y; return result; // Must return an int } public String getGreeting(String name) { return "Hello, " + name + "!"; // Returns a String } public boolean isEven(int number) { return number % 2 == 0; // Returns true or false } // STATIC METHOD - Belongs to class, not objects public static double calculateCircleArea(double radius) { return Math.PI * radius * radius; } // INSTANCE METHOD - Belongs to objects private String userName; public void setUserName(String name) { this.userName = name; // Uses 'this' to refer to current object } public String getUserName() { return this.userName; } // Main method - static and special public static void main(String[] args) { // Creating object to use instance methods MethodTypesDemo demo = new MethodTypesDemo(); // Calling void method demo.printWelcome(); // Calling return methods int product = demo.multiply(5, 6); System.out.println("5 × 6 = " + product); // 30 String greeting = demo.getGreeting("Alice"); System.out.println(greeting); // Hello, Alice! boolean check = demo.isEven(10); System.out.println("Is 10 even? " + check); // true // Calling static method (no object needed) double area = calculateCircleArea(5.0); System.out.println("Circle area: " + area); // Using instance methods demo.setUserName("Bob"); System.out.println("User: " + demo.getUserName()); }}📥 Parameters and Arguments
How methods receive and work with data:
Parameters (in definition):
The variables listed in the method definition. Think of them as empty boxes waiting for values.
Arguments (in call):
The actual values you pass when calling the method. These fill the empty boxes.
public class ParametersDemo { // Method with parameters // ↓ parameters (variables) public void printInfo(String name, int age, double height) { System.out.println("Name: " + name); System.out.println("Age: " + age); System.out.println("Height: " + height + " meters"); } // Method with no parameters public void sayHello() { System.out.println("Hello!"); } // Method demonstrating pass-by-value public void tryToModify(int number) { number = number + 10; // Only changes local copy System.out.println("Inside method: " + number); } // Method with array parameter public void printArray(int[] numbers) { for (int num : numbers) { System.out.print(num + " "); } System.out.println(); } // Variable arguments (varargs) public int sum(int... numbers) { int total = 0; for (int num : numbers) { total += num; } return total; } public static void main(String[] args) { ParametersDemo demo = new ParametersDemo(); // Calling with arguments // ↓ arguments (actual values) demo.printInfo("Alice", 25, 1.65); demo.printInfo("Bob", 30, 1.80); // No arguments demo.sayHello(); // Pass-by-value demonstration int x = 5; System.out.println("Before: " + x); // 5 demo.tryToModify(x); // Inside: 15 System.out.println("After: " + x); // Still 5! (not changed) // Array parameter int[] scores = {85, 92, 78, 95}; demo.printArray(scores); // Varargs - can pass any number of arguments System.out.println("Sum: " + demo.sum(1, 2, 3)); // 6 System.out.println("Sum: " + demo.sum(10, 20, 30, 40)); // 100 System.out.println("Sum: " + demo.sum(5)); // 5 }}📤 Return Values
How methods give back results:
public class ReturnDemo { // Returns int public int getAge() { return 25; } // Returns String public String getName() { return "Alice"; } // Returns boolean public boolean isAdult(int age) { if (age >= 18) { return true; // Early return } return false; } // Multiple return statements public String getGrade(int score) { if (score >= 90) return "A"; if (score >= 80) return "B"; if (score >= 70) return "C"; if (score >= 60) return "D"; return "F"; // Default case - ensures a return } // Returns array public int[] getScores() { int[] scores = {85, 92, 78, 95, 88}; return scores; } // Returns object public Person createPerson(String name, int age) { Person p = new Person(name, age); return p; } // Void - returns nothing public void displayMessage() { System.out.println("This method returns nothing"); return; // Optional in void methods } // Calculates and returns public double calculateDiscount(double price, double percentage) { double discount = price * (percentage / 100); return discount; } public static void main(String[] args) { ReturnDemo demo = new ReturnDemo(); // Using return values int age = demo.getAge(); System.out.println("Age: " + age); String name = demo.getName(); System.out.println("Name: " + name); boolean adult = demo.isAdult(20); System.out.println("Is adult? " + adult); String grade = demo.getGrade(85); System.out.println("Grade: " + grade); // Using returned array int[] scores = demo.getScores(); System.out.println("First score: " + scores[0]); // Direct use in expressions if (demo.isAdult(16)) { System.out.println("Can vote"); } else { System.out.println("Too young"); // This runs } // Calculate discount double finalPrice = 100.0 - demo.calculateDiscount(100.0, 20); System.out.println("Final price: $" + finalPrice); // $80.0 }}class Person { String name; int age; Person(String name, int age) { this.name = name; this.age = age; }}🔀 Method Overloading
Same name, different signatures:
public class OverloadingDemo { // Same name, different number of parameters public int add(int a, int b) { return a + b; } public int add(int a, int b, int c) { return a + b + c; } // Same name, different parameter types public double add(double a, double b) { return a + b; } // Print methods - common overloading example public void print(String message) { System.out.println("String: " + message); } public void print(int number) { System.out.println("Integer: " + number); } public void print(double number) { System.out.println("Double: " + number); } public void print(boolean value) { System.out.println("Boolean: " + value); } // Calculate area - overloaded for different shapes public double calculateArea(double radius) { // Circle return Math.PI * radius * radius; } public double calculateArea(double length, double width) { // Rectangle return length * width; } public double calculateArea(double base, double height, boolean isTriangle) { // Triangle (third param just to differentiate) return 0.5 * base * height; } public static void main(String[] args) { OverloadingDemo demo = new OverloadingDemo(); // Java chooses the right method based on arguments System.out.println("2 + 3 = " + demo.add(2, 3)); // Calls add(int, int) System.out.println("1 + 2 + 3 = " + demo.add(1, 2, 3)); // Calls add(int, int, int) System.out.println("2.5 + 3.5 = " + demo.add(2.5, 3.5)); // Calls add(double, double) // Print overloading demo.print("Hello"); // Calls print(String) demo.print(42); // Calls print(int) demo.print(3.14); // Calls print(double) demo.print(true); // Calls print(boolean) // Area calculations System.out.println("Circle area: " + demo.calculateArea(5.0)); System.out.println("Rectangle area: " + demo.calculateArea(4.0, 6.0)); System.out.println("Triangle area: " + demo.calculateArea(4.0, 6.0, true)); // ❌ NOTE: Cannot overload by return type alone! // These would cause error: // public int getValue() { return 1; } // public double getValue() { return 1.0; } // ERROR! }}🔄 Bonus: Recursion (Method Calling Itself)
public class RecursionDemo { // Factorial: 5! = 5 × 4 × 3 × 2 × 1 = 120 public int factorial(int n) { // Base case - when to stop if (n <= 1) { return 1; } // Recursive case - method calls itself return n * factorial(n - 1); } // Fibonacci: 0, 1, 1, 2, 3, 5, 8, 13... public int fibonacci(int n) { if (n <= 1) { return n; } return fibonacci(n - 1) + fibonacci(n - 2); } // Count down public void countdown(int n) { if (n <= 0) { System.out.println("Blast off!"); return; } System.out.println(n); countdown(n - 1); // Calls itself with smaller number } // Sum of digits: 123 → 1 + 2 + 3 = 6 public int sumOfDigits(int number) { if (number == 0) { return 0; } return (number % 10) + sumOfDigits(number / 10); } public static void main(String[] args) { RecursionDemo demo = new RecursionDemo(); // Factorial System.out.println("5! = " + demo.factorial(5)); // 120 // Fibonacci System.out.println("Fibonacci(6) = " + demo.fibonacci(6)); // 8 // Countdown demo.countdown(5); // Sum of digits System.out.println("Sum of digits in 123: " + demo.sumOfDigits(123)); // 6 // ⚠️ WARNING: Always have a base case! // Without it, you get infinite recursion (stack overflow) }}✨ Best Practices
- ✓Use descriptive method names: calculateTotal() not calc()
- ✓Keep methods short and focused (do one thing well)
- ✓Use verb names for methods: getName(), setAge(), printReport()
- ✓Limit parameters to 3-4 (too many makes it complex)
- ✓Don't modify parameters (use local variables instead)
- ✓Document complex methods with comments
- ✓Follow naming convention: camelCase for method names
💼 Interview Tips
- 💡Understand the difference between parameters and arguments
- 💡Know static vs instance methods - very common interview question
- 💡Remember: method signature = name + parameter types (not return type)
- 💡Be ready to explain method overloading with examples
- 💡Understand pass-by-value in Java (primitives copy value, objects copy reference)
- 💡Know when to use void vs return types
- 💡Understand recursion basics (method calling itself)
⚠️ Common Mistakes
- ✗Forgetting to return a value in non-void methods
- ✗Trying to use local variables from one method in another
- ✗Calling instance methods without creating an object first
- ✗Confusing parameters (in definition) with arguments (in call)
- ✗Overloading methods that differ only by return type (doesn't work!)
- ✗Creating methods that do too many things (violates single responsibility)
- ✗Not handling all possible return paths in conditional code