Skip to main content

Methods

Methods

Complete lesson for Methods using LEARNCODEGURU’s 6-level learning model — from basics to advanced practice, with Java OOP and Collections where relevant.

L1

Basics — Methods

Section: Methods. Java methods (not free functions): signature, instance vs static, overloading, varargs, pass-by-value, and return types.

What is a method?

  • A method is a named block of code that belongs to a class or to an object. It can take parameters, do work, and optionally return a value.
  • Java has no free-standing functions like C or Python. Every piece of behavior lives inside a class as a method (instance or static).
  • Real-life idea: a method is a skill of a type — Account.deposit, String.length, Math.max — not a loose recipe sitting outside any type.
PartMeaningExample
NameHow you call itadd, greet, main
ParametersInput valuesint a, int b
Return typeWhat comes backint, String, void
BodyThe statements that run{ return a + b; }
public class MethodBasics {
    static int add(int a, int b) {
        return a + b;
    }

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

    public static void main(String[] args) {
        greet("Ada");
        System.out.println(add(2, 3));
    }
}

Differences between function and method

  • In theory, a function is a reusable procedure. A method is a function that belongs to an object or a class.
  • C and C++ allow free functions (int add(int a, int b) at file scope). Java does not — add must sit inside a class.
  • People still say “function” in casual talk. In Java interviews, say method. C++ member functions are methods; free functions are not.
PointFunctionMethod
DefinitionA standalone reusable block of codeA function that belongs to a class or object
Where it livesFile / namespace / module (C, C++, Python)Always inside a class (Java)
Java supportNo top-level functionsThe only option — instance or static
Typical calladd(2, 3) with no ownerobj.add(2, 3) or Math.max(2, 3)
this / receiverNoneInstance methods have this (the current object)
Access to fieldsOnly through argumentsCan read/write the object’s fields (if instance)
OOP roleOptional helperThe unit of behavior in a class
C / C++Free function is normalMember function = method
Pythondef add(a, b): at module leveldef add(self, b): on a class
Lambdas in JavaNot free functionsObjects that implement a functional interface (still methods under the hood)

Anatomy of a Java method

  • Order: modifiers, return type, name, parameter list, optional throws, then a body (or ; if abstract / native).
  • void means no return value. return; exits early from a void method. A non-void method must return on every path.
  • Access modifiers (public, private, protected, package-private) control who can call the method.
PieceRequired?Notes
ModifiersNopublic, static, final, abstract, …
Return typeYesvoid or a type (int, String, …)
NameYesVerb style: calculateTax
(parameters)Yes (may be empty)Types + names; varargs last
throws listNoChecked exceptions the caller must handle
{ body }Yes (unless abstract/native)The work

Instance methods vs static methods

  • Instance methods need an object. They can use this and instance fields.
  • static methods belong to the class. Call them as ClassName.method(...). They cannot use this or instance fields.
  • Real-life: account.deposit(100) is instance (this account). Math.max(a, b) is static (no particular Math object).
PointInstance methodStatic method
Belongs toAn objectThe class
Callobj.work()Class.work()
thisYesNo
Instance fieldsYesNo (only static fields)
Typical useObject behaviorUtilities, main, factories
public class Account {
    int balance;

    void deposit(int amount) {
        this.balance += amount;
    }

    static int max(int a, int b) {
        return a > b ? a : b;
    }

    public static void main(String[] args) {
        Account a = new Account();
        a.deposit(50);
        System.out.println(a.balance);
        System.out.println(Account.max(3, 9));
    }
}

Overloading vs overriding (preview)

  • Overloading: same method name, different parameter lists, chosen at compile time. Return type alone cannot distinguish overloads.
  • Overriding: same signature in a subclass, chosen at runtime — covered fully under polymorphism.
IdeaOverloadingOverriding
WhereSame class (or inherited name)Subclass / implementing class
ParametersMust differMust match (same signature)
When chosenCompile timeRuntime (virtual dispatch)
KeywordsNone special@Override, cannot be static

Varargs and pass-by-value

  • void log(String... parts) is an array parameter. It must be the last parameter. A call log() passes a zero-length array, not null.
  • Java is pass-by-value. For primitives the bits are copied. For objects the reference is copied: the method can mutate the object, but obj = somethingElse does not change the caller variable.
public class PassByValue {
    static void bump(int n) {
        n = 100;
    }

    static void addItem(java.util.ArrayList<String> list) {
        list.add("x");
    }

    public static void main(String[] args) {
        int n = 1;
        bump(n);
        System.out.println(n); // still 1
        java.util.ArrayList<String> list = new java.util.ArrayList<>();
        addItem(list);
        System.out.println(list); // [x]
    }
}
L2

Advanced — Methods

Signatures, hiding, and main

  • The JVM signature is name + parameter types (type erasure applies to generics). throws is not part of the overload key.
  • A static method with the same signature in a subclass hides the parent method; it does not override.
  • main can be overloaded, but the launcher only calls public static void main(String[]).
  • Avoid too many overloads that differ only by int vs Integer or array vs varargs — the compiler most-specific rule surprises people.

Why Java uses methods, not free functions

  • Encapsulation: behavior stays next to the data it uses (balance + deposit).
  • Polymorphism needs methods on types so a subclass can override draw() or compareTo.
  • You can still write “function-like” code as static helpers (Math, Collections) — they are methods on a class, not file-scope functions.
  • Java 8+ lambdas look like tiny functions, but they compile to objects with a single method (apply, test, run).
L3

Tricky Interview Points

Q1) Difference between a function and a method?

Answer A function is a standalone reusable block. A method is a function that belongs to a class or object. Java has only methods — no top-level functions like C or Python.

Q2) Does Java have functions?

Answer Not as top-level functions. You write methods on classes (instance or static). Lambdas are instances of functional interfaces, not free functions.

Q3) What is pass-by-value in Java?

Answer Arguments are copied. For primitives the bits are copied. For objects the reference is copied, so the callee can change the object state but not the caller reference variable.

Q4) Can you overload by return type only?

Answer No. The parameter list must differ. Return type is not part of the overload identity.

Q5) What are varargs?

Answer A variable-arity parameter written Type... name. The compiler packs arguments into an array. Only one varargs, and it must be last.

Q6) static method vs instance method?

Answer static belongs to the class and cannot use this or instance fields. Instance methods need an object and can use this.

Q7) Is main a special keyword?

Answer No. It is a method the launcher looks up by signature. You can have other methods named main.

Q8) What is a method signature in Java?

Answer Name plus parameter types. Modifiers, return type, and throws are not part of the overload signature.

Q9) Can a static method call an instance method?

Answer Only through an object reference. From main you write obj.work(), not work(), unless work is also static.

Q10) C++ free function vs Java static method?

Answer A C++ free function lives at namespace/file scope. A Java static method still belongs to a class (Math.max). Same call style, different ownership.

L4

Simple Programs

Instance method vs static helper

public class TempConverter {
    double celsius;

    void setCelsius(double c) {
        this.celsius = c;
    }

    double toFahrenheit() {
        return celsius * 9 / 5 + 32;
    }

    static double freezePointF() {
        return 32;
    }

    public static void main(String[] args) {
        TempConverter t = new TempConverter();
        t.setCelsius(100);
        System.out.println(t.toFahrenheit());
        System.out.println(TempConverter.freezePointF());
    }
}

Overload and varargs

public class OverloadDemo {
    static int max(int a, int b) {
        return a > b ? a : b;
    }

    static int max(int a, int b, int c) {
        return max(max(a, b), c);
    }

    static int sum(int... nums) {
        int s = 0;
        for (int n : nums) s += n;
        return s;
    }

    public static void main(String[] args) {
        System.out.println(max(4, 9));
        System.out.println(max(4, 9, 1));
        System.out.println(sum(1, 2, 3, 4));
    }
}

Pass-by-value for int vs list

import java.util.ArrayList;

public class PassDemo {
    static void setZero(int n) {
        n = 0;
    }

    static void clear(ArrayList<String> list) {
        list.clear();
    }

    public static void main(String[] args) {
        int n = 7;
        setZero(n);
        System.out.println(n); // 7
        ArrayList<String> list = new ArrayList<>();
        list.add("keep?");
        clear(list);
        System.out.println(list.size()); // 0
    }
}
L5

Problem Solving Tricks

  • Name methods as verbs: calculateTax, not tax.
  • Keep parameter lists short; wrap many options in an object or a builder.
  • Do not overload static and instance methods with the same name unless you enjoy confusing readers.
  • Document units (millis, indexInclusive) in the method name or Javadoc.
  • Say method in Java interviews, not function — unless you are contrasting with C/C++.
  • Call static methods on the class name (Math.max), not on an instance.
  • A void method can still change object state; “no return” is not “no effect”.
L6

Practice Programs List

  1. Write a class Box with instance methods setSize and volume, plus a static cubeVolume(int side).
  2. Write overloaded area methods for circle (radius) and rectangle (width, height).
  3. Write average(double... values) that throws if length is 0.
  4. Show pass-by-value: a method that does x = 100 on an int and one that does list.add on an ArrayList.
  5. Overload print for int, String, and int[].
  6. Split a god method that reads, computes, and prints into three methods.
  7. From main, call an instance method (need new) and a static method (class name).
  8. Explain in comments why add(2, 3) is illegal in Java unless add is static in the same class (or imported statically).
  9. Write two classes and show that a method in A cannot be called like a C function from B without A or an A object.
  10. List three real-life examples of instance methods and three of static methods.