Board Formulas
β˜• JavaπŸ“… Day 9

Methods in Java

Define, call and overload methods. Parameters, return types and scope.

🎯

Learning objectives

  • β†’Declare methods with return types and parameters
  • β†’Call methods and use return values
  • β†’Overload methods for cleaner APIs

πŸ’‘ Key points

  • Signature: [modifiers] returnType name(paramList) { body }
  • Return type void = no value returned. Any other type must have a return statement.
  • Parameters are passed by value in Java β€” including object references (the reference itself is copied).
  • Overloading: same name, different parameter lists. Different return type alone is NOT enough.

πŸ’» Code examples(4)

#1Simple method
java
public class Calc {
    static int add(int a, int b) {
        return a + b;
    }

    public static void main(String[] args) {
        int sum = add(3, 4);
        System.out.println(sum);
    }
}
Output
7
static means the method belongs to the class, callable without an object. Non-static needs an instance.
#2void method
java
static void greet(String name) {
    System.out.println("Hello, " + name);
}

greet("Priya");
No return value. return; (without expression) can exit early if needed.
#3Method overloading
java
static int area(int side) {
    return side * side;              // square
}

static int area(int l, int w) {
    return l * w;                     // rectangle
}

static double area(double r) {
    return Math.PI * r * r;           // circle
}
Same name, different parameter counts/types. Compiler picks the right one from the arguments.
#4Pass by value pitfall
java
static void addOne(int x) {
    x = x + 1;   // local copy modified
}

public static void main(String[] args) {
    int n = 5;
    addOne(n);
    System.out.println(n);  // still 5!
}
Primitives are copied. Method changes don't reach the caller. Return a new value instead: n = addOne(n).

🎯 Practice

Q1. Can two methods differ only in return type?+

No. Java requires the parameter list to differ. Same params + different return = compile error.

Q2. Write a method that returns the larger of two ints.+

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

Q3. What does 'pass by value' mean for objects?+

The reference (address) is copied. Both caller and method point to the same object β€” mutations inside the method are visible outside. But reassigning the parameter to a new object is invisible to the caller.

πŸ“ Notes

Return early to keep code flat

static String grade(int marks) {
    if (marks < 0 || marks > 100) return "Invalid";
    if (marks >= 90) return "A+";
    if (marks >= 75) return "A";
    if (marks >= 60) return "B";
    return "C";
}

Multiple returns are fine β€” Java has no penalty. Nested if-else pyramids are worse.

Naming conventions

  • Use verbs: calculateTax, printReport, isValid.
  • Boolean-returning methods start with is, has, can: isEmpty(), hasNext().
  • Keep methods short β€” one job each. If it can't be described in one sentence, split it.