JAVA • Intermediate

Java Methods

A method is a block of code that performs a specific task and can be called multiple times. Methods make your code reusable, modular, and readable. In Java, every method must belong to a class — there are no standalone functions.

What is a Method?

Instead of writing the same logic repeatedly, you define it once as a method and call it whenever needed. This reduces code duplication and makes debugging easier.

Method Syntax

accessModifier returnType methodName(parameters) {
    // method body
    return value;  // if returnType is not void
}

Example

public static int add(int a, int b) {
    return a + b;
}
  • public — access modifier (visible everywhere)
  • static — belongs to class, no object needed
  • int — return type
  • add — method name
  • int a, int b — parameters
  • return a + b — returns the result

Your First Method

public class Demo {

    public static void greet() {
        System.out.println("Hello from Varanasi!");
    }

    public static void main(String[] args) {
        greet();   // Call the method
        greet();   // Call again
    }
}

// Output:
// Hello from Varanasi!
// Hello from Varanasi!

Methods with Parameters

public static void greet(String name) {
    System.out.println("Hello, " + name + "!");
}

public static void main(String[] args) {
    greet("Ankit");     // Hello, Ankit!
    greet("Priya");     // Hello, Priya!
}

Methods with Return Values

public static int square(int n) {
    return n * n;
}

public static double average(int a, int b) {
    return (a + b) / 2.0;
}

public static String getGreeting(String name) {
    return "Hello, " + name;
}

public static void main(String[] args) {
    System.out.println(square(5));           // 25
    System.out.println(average(10, 20));     // 15.0
    System.out.println(getGreeting("Ankit"));// Hello, Ankit
}
💡 Academy Tip

Use void when the method doesn't return a value. Use a specific type (int, String, etc.) when it does. void methods can still print or modify external state.

Static vs Instance Methods

Static Method

Belongs to the class. Can be called without creating an object. Uses static keyword.

public class MathUtil {
    public static int add(int a, int b) {
        return a + b;
    }
}

// Call without object
int sum = MathUtil.add(10, 20);
System.out.println(sum);   // 30

Instance Method

Belongs to an object. Requires creating an instance to call.

public class Calculator {
    public int add(int a, int b) {   // no static
        return a + b;
    }
}

// Call with object
Calculator calc = new Calculator();
int sum = calc.add(10, 20);
System.out.println(sum);   // 30

When to use which?

  • Static — utility methods (math, validation, conversion) that don't depend on instance state.
  • Instance — methods that operate on object data (like Student.getName()).

Method Overloading

Two or more methods with the same name but different parameters. Return type alone is not enough to overload.

public class Calculator {

    public int add(int a, int b) {
        return a + b;
    }

    public int add(int a, int b, int c) {
        return a + b + c;
    }

    public double add(double a, double b) {
        return a + b;
    }

    public static void main(String[] args) {
        Calculator c = new Calculator();
        System.out.println(c.add(10, 20));         // 30
        System.out.println(c.add(10, 20, 30));     // 60
        System.out.println(c.add(2.5, 3.7));       // 6.2
    }
}
⚠ Rule

Method overloading is determined by number, types, and order of parameters. Changing only the return type (e.g., int add() vs double add()) is NOT valid overloading — compile error.

Returning Multiple Values

Java methods return only one value. To return multiple values, use:

Option 1: Array

public static int[] minMax(int[] arr) {
    int min = arr[0], max = arr[0];
    for (int n : arr) {
        if (n < min) min = n;
        if (n > max) max = n;
    }
    return new int[]{min, max};
}

int[] result = minMax(new int[]{5, 2, 8, 1, 9});
System.out.println("Min: " + result[0] + ", Max: " + result[1]);

Option 2: Object

class Result {
    int min, max;
    Result(int min, int max) {
        this.min = min;
        this.max = max;
    }
}

public static Result minMax(int[] arr) {
    // ... compute
    return new Result(min, max);
}

Recursion — Method Calling Itself

A recursive method calls itself with a smaller input. Every recursive method must have a base case to stop.

Factorial

public static int factorial(int n) {
    if (n == 0 || n == 1) {
        return 1;              // base case
    }
    return n * factorial(n - 1);   // recursive case
}

System.out.println(factorial(5));   // 120

Fibonacci

public static int fib(int n) {
    if (n <= 1) return n;
    return fib(n - 1) + fib(n - 2);
}

for (int i = 0; i < 8; i++) {
    System.out.print(fib(i) + " ");
}
// Output: 0 1 1 2 3 5 8 13
💡 Academy Tip

Recursion is elegant but can be slow for large inputs and can cause StackOverflowError. For performance-critical code, prefer iteration (loops).

Pass by Value

Java is always pass-by-value. When you pass a primitive, the method gets a copy. When you pass an object reference, the method gets a copy of the reference (but both point to the same object).

public static void change(int x) {
    x = 100;
}

public static void main(String[] args) {
    int a = 5;
    change(a);
    System.out.println(a);   // 5 — NOT changed
}

Real-World Example — Calculator Class

public class Calculator {

    public static int add(int a, int b) {
        return a + b;
    }

    public static int subtract(int a, int b) {
        return a - b;
    }

    public static int multiply(int a, int b) {
        return a * b;
    }

    public static double divide(int a, int b) {
        if (b == 0) {
            System.out.println("Cannot divide by zero");
            return 0;
        }
        return (double) a / b;
    }

    public static void main(String[] args) {
        System.out.println("Sum: " + add(10, 5));
        System.out.println("Diff: " + subtract(10, 5));
        System.out.println("Product: " + multiply(10, 5));
        System.out.println("Quotient: " + divide(10, 5));
    }
}

Method Naming Conventions

  • Use camelCase — calculateTotal, getUserName
  • Start with a verb — get, set, is, has, calculate
  • Getters — getName()
  • Setters — setName()
  • Boolean checks — isActive(), hasPermission()
📝 Try Yourself

1. Write a method isEven(int n) that returns true if the number is even.
2. Write a method max(int a, int b, int c) that returns the largest of three.
3. Write a method reverse(String s) that returns the reversed string.
4. Write an overloaded method area() — one for circle (radius), one for rectangle (length, width).
5. Write a recursive method sum(int n) that returns the sum of 1 to n.

Quick Revision

  • Method = reusable block of code inside a class.
  • Syntax: accessModifier returnType name(params) { ... }
  • void = no return value.
  • static methods don't need an object.
  • Overloading = same name, different parameters.
  • Java passes everything by value.
  • Recursion needs a base case.
  • Naming: camelCase, verb-first.
  • Use arrays or objects to return multiple values.

Interview Questions

Q: Difference between method overloading and overriding?

A: Overloading — same method name, different parameters, in the same class. Overriding — subclass provides a new implementation of a parent class method with the same signature. Overloading is compile-time; overriding is runtime.

Q: What is the difference between static and instance methods?

A: Static methods belong to the class, called via ClassName.method(), and cannot access instance variables directly. Instance methods require an object and can access all instance variables.

Q: Is Java pass-by-value or pass-by-reference?

A: Java is always pass-by-value. For primitives, the value is copied. For objects, the reference is copied — so you can modify the object's contents, but you cannot change which object the reference points to.

Q: Can a Java method return multiple values?

A: No, a method can return only one value. To return multiple values, wrap them in an array, an object, or use Map.

Q: What is method overloading? Give an example.

A: Same method name, different parameter list. Example: add(int a, int b) and add(int a, int b, int c) and add(double a, double b). Return type alone is not enough.

Q: What is recursion? What are its downsides?

A: A method that calls itself. It's elegant for tree-like problems and factorials but uses more memory (stack) and can cause StackOverflowError if too deep. Prefer iteration for large inputs.

Q: What happens if we don't use return in a method with non-void return type?

A: Compile error — "missing return statement". Every code path must return a value for non-void methods.

Want to Master Java?

Join our Java course in Varanasi — practical classes and career support at our Sarnath centre.

Ask on WhatsApp
Chat with us