Methods — Signatures, Overloading, Varargs

মেথড — signature, overloading, varargs

Read: ~30 min Intermediate 5 practice problems Live code runner

1. Methods — Java's Unit of Abstraction

A method is a named chunk of code you can call. It takes parameters, runs, and optionally returns a value. Well-named methods are how large Java programs stay readable — every method should do one thing and have a name that says so.

Method হলো একটি নাম-দেওয়া কোড-খণ্ড যা parameter নিয়ে কাজ করে, ঐচ্ছিকভাবে value return করে। বড় প্রোগ্রামকে পরিষ্কার রাখার প্রধান অস্ত্র — প্রতিটি method-এর একটি-ই কাজ থাকবে, এবং নাম সেটিই বলবে।

2. Anatomy of a Method Signature

Main.java
class Main {
    // modifiers  return  name       parameters              body
    public static int square(int n) {
        return n * n;
    }

    static double average(int a, int b, int c) {
        return (a + b + c) / 3.0;
    }

    static void greet(String name) {           // void = no return
        System.out.println("Hello, " + name);
    }

    public static void main(String[] args) {
        System.out.println(square(7));
        System.out.println(average(80, 90, 75));
        greet("Arif");
    }
}
Method-এর গঠন — modifiers (public/static), return type, name, parentheses-এ parameter list, এবং body। void মানে কোনো মান return করে না। Signature = নাম + parameter type-গুলোর ক্রম (return type signature-এর অংশ নয় overloading-এর জন্য)।

3. static vs Instance Methods

A static method belongs to the class; call it as Math.sqrt(25). An instance method belongs to an object; you must have an object to call it — "hello".toUpperCase().

Main.java
class Wallet {
    double balance;

    Wallet(double b) { balance = b; }

    // instance method — needs a specific Wallet
    void deposit(double amt) { balance += amt; }

    // static method — no object required
    static Wallet openNew(double opening) {
        return new Wallet(opening);
    }
}

class Main {
    public static void main(String[] args) {
        Wallet w = Wallet.openNew(500);  // static call
        w.deposit(200);                    // instance call
        System.out.println("balance = " + w.balance);
    }
}
static method class-এর সঙ্গে যুক্ত (ClassName.method())। Instance method object-এর সঙ্গে (object.method())। Math.sqrt static, "hi".toUpperCase() instance।

4. Method Overloading

Java lets multiple methods share a name as long as their parameter lists differ — this is overloading. The compiler picks the right one based on the argument types at the call site.

Main.java
class Main {
    static int add(int a, int b)           { return a + b; }
    static double add(double a, double b)  { return a + b; }
    static int add(int a, int b, int c)   { return a + b + c; }
    static String add(String a, String b)  { return a + b; }

    public static void main(String[] args) {
        System.out.println(add(2, 3));
        System.out.println(add(2.5, 3.5));
        System.out.println(add(1, 2, 3));
        System.out.println(add("Hello, ", "World"));
    }
}
Overloading rules:
  • Parameter lists must differ in type, order, or count.
  • Return type alone cannot distinguish overloads.
  • The compiler picks the most specific matching version.
Overloading মানে একই নামের একাধিক method, কিন্তু parameter list আলাদা। Return type শুধু আলাদা হলেই হবে না। Compiler call-এর সময় argument দেখে সঠিক version বেছে নেয়।

5. Varargs — Variable Number of Arguments

Writing int... lets a method accept zero or more arguments of that type. Inside the method, args is a regular array.

Main.java
class Main {
    static int sum(int... nums) {       // varargs
        int total = 0;
        for (int n : nums) total += n;
        return total;
    }

    static String join(String sep, String... parts) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < parts.length; i++) {
            if (i > 0) sb.append(sep);
            sb.append(parts[i]);
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        System.out.println(sum());                   // 0
        System.out.println(sum(10));                 // 10
        System.out.println(sum(10, 20, 30, 40));     // 100
        System.out.println(join(" · ", "Dhaka", "Chattogram", "Sylhet"));
    }
}
Varargs rules: there can be at most one varargs parameter, and it must be the last one. Inside the method it's a real array — use length and indexing as usual.
int... nums মানে 0 বা তার বেশি int — method-এর ভেতরে এটি একটি array। প্রতিটি method-এ সর্বোচ্চ একটি varargs, এবং সেটি হতে হবে সর্বশেষ parameter। System.out.printf এভাবেই কাজ করে।

6. Java Is Always Pass-by-Value

When you call a method, Java copies each argument into a new local variable. For primitives that is the value itself; for objects it is the reference (the address), not the object. So a method can mutate the object through its reference, but it can't make the caller's variable point to a new object.

Main.java
import java.util.*;

class Main {
    static void tryChangePrimitive(int x) { x = 999; }   // no effect outside
    static void tryChangeRef(List<Integer> list) {
        list.add(99);                    // ✅ mutates same object
        list = new ArrayList<>();       // ❌ only local rebinding
        list.add(1000);
    }

    public static void main(String[] args) {
        int a = 5;
        tryChangePrimitive(a);
        System.out.println("primitive a still " + a);   // 5

        List<Integer> xs = new ArrayList<>();
        xs.add(1); xs.add(2);
        tryChangeRef(xs);
        System.out.println("list now " + xs);  // [1, 2, 99]
    }
}
Java সবসময় pass-by-value। primitive-এর মান copy হয় — ভেতরে বদলালে বাইরের variable অপরিবর্তিত। object-এর reference-এর copy যায় — তাই method-এ সেই object-এর state বদলানো যায়, কিন্তু caller-এর variable-কে নতুন object-এ point করানো যায় না।

7. Good Method Style

  • One verb per name: sendMoney, not doStuff.
  • Keep methods short — a screenful or less is a great target.
  • Avoid more than 4 parameters — group related arguments into a class/record.
  • Prefer return values over output parameters.
  • Avoid modifying caller-supplied collections unless the method name clearly says so.
ভালো method — একটি verb-এর নাম, ছোট, অল্প parameter, স্পষ্ট return। অনেক parameter হলে ছোট class/record বানিয়ে নিন। অন্যের দেওয়া Collection বদলানো থেকে সাধারণত বিরত থাকুন।

8. Vocabulary

TermMeaningবাংলায়
SignatureMethod name + parameter types & order.নাম + parameter list।
Return typeType of value the method returns (or void).method যে type return করে।
OverloadingMultiple methods with same name, different params.একই নামে বিভিন্ন parameter।
VarargsT... — any number of T arguments.variable-length argument list।
Static methodBelongs to the class, not to an instance.class-এর method, object লাগে না।
Pass-by-valueArguments are copied into parameters.argument copy হয়ে parameter-এ যায়।

9. Practice Problems

  1. Write a static method max3(int a, int b, int c) that returns the largest of three integers. Call it in main.
    তিনটি integer-এর সর্বোচ্চ return করার static method লিখুন।
    ✨ Show Answer (উত্তর দেখুন)
    Main.java
    class Main {
        static int max3(int a, int b, int c) {
            return Math.max(a, Math.max(b, c));
        }
        public static void main(String[] args) {
            System.out.println(max3(12, 47, 33));
        }
    }
  2. Overload area for a square (one side) and a rectangle (width, height).
    square ও rectangle-এর জন্য area overload করুন।
    ✨ Show Answer (উত্তর দেখুন)
    Main.java
    class Main {
        static double area(double side) { return side * side; }
        static double area(double w, double h) { return w * h; }
        public static void main(String[] args) {
            System.out.println(area(4));
            System.out.println(area(3, 5));
        }
    }
  3. Write a varargs method printAll(String... items) that prints each item on a new line and the total count at the end.
    varargs printAll method তৈরি করুন।
    ✨ Show Answer (উত্তর দেখুন)
    Main.java
    class Main {
        static void printAll(String... items) {
            for (String s : items) System.out.println("- " + s);
            System.out.println("total: " + items.length);
        }
        public static void main(String[] args) {
            printAll("Dhaka", "Rajshahi", "Barishal");
        }
    }
  4. Explain in 3 sentences why "Java is pass-by-value" does NOT contradict the fact that a method can modify an object you pass in.
    Java pass-by-value হওয়া সত্ত্বেও object-এর state পাল্টানো যায় — ব্যাখ্যা করুন।
    ✨ Show Answer (উত্তর দেখুন)

    Answer: When you pass an object reference, Java copies the reference value — not the object. The caller and callee now hold two references to the same heap object, so mutating a field through the copied reference is visible everywhere. What the method cannot do is reassign the caller's variable to point to a new object — that reassignment is purely local, because the original variable was never passed, only its reference value.

  5. Write a method stats(int... ns) that returns a String with the count, sum, and average (to 2 decimals) of the inputs.
    varargs দিয়ে count, sum, average ফেরাবে এমন stats method লিখুন।
    ✨ Show Answer (উত্তর দেখুন)
    Main.java
    class Main {
        static String stats(int... ns) {
            if (ns.length == 0) return "(no data)";
            long sum = 0;
            for (int n : ns) sum += n;
            double avg = (double) sum / ns.length;
            return String.format("count=%d sum=%d avg=%.2f", ns.length, sum, avg);
        }
        public static void main(String[] args) {
            System.out.println(stats(10, 20, 30, 40));
            System.out.println(stats());
        }
    }

Summary — Module 11

A method's signature is name + parameter types. Java supports overloading (same name, different parameter lists) and varargs (T...) for flexible APIs. Static methods belong to the class; instance methods belong to objects. Java always passes arguments by value — for objects that means copying the reference, which is why a method can mutate the object but cannot make the caller's variable point elsewhere. Keep methods short, single-purpose, and clearly named.

Method = নাম + parameter type; overloading + varargs নমনীয় API দেয়। static vs instance — class বনাম object-এর method। Java সর্বদা pass-by-value — object-এর state বদলানো যায়, variable-কে নতুন object-এ point করানো যায় না।

Next Module → Classes, Objects, and Constructors — the heart of Java OOP.