Skip to content

Beginner · Control flow and methods · topic 9 of 60 · 30 min

Methods: parameters, return values and overloading

Explanation

A method is a named block of code inside a class, called with arguments and optionally returning a value. Java passes arguments by value: primitives are copied, and for objects the reference is copied, so a method can change an object's contents but not make the caller's variable point elsewhere. Overloading means several methods with the same name but different parameter lists.

Why methods?

A method packages one job under a name: calculateGst, isValidPan, printReceipt. You write the logic once and call it wherever needed. Short methods with clear names make programs readable and testable. In this module our methods are static, meaning they belong to the class and can be called without creating an object; module 4 introduces instance methods.

java
public class Billing {
    static double withGst(double amount, double ratePercent) {
        return amount + amount * ratePercent / 100;
    }

    static void printLine(String item, double price) {   // void: returns nothing
        System.out.printf("%-10s Rs %8.2f%n", item, price);
    }

    public static void main(String[] args) {
        double total = withGst(1000, 18);   // 1180.0
        printLine("Total", total);
    }
}

Signature and return

A method's signature is its name plus its parameter types: withGst(double, double). The return type comes before the name. A non-void method must return a value on every path, or it does not compile ("missing return statement"). return also ends the method immediately.

Pass-by-value, precisely

Java ALWAYS passes a copy of the argument. For a primitive, the copy is the number itself, so the method cannot change the caller's variable. For an object, the copy is the reference (the address), so the method can change the object it points to, but reassigning the parameter only changes the method's local copy.

java
static void addBonus(int salary) { salary += 5000; }
static void addItem(java.util.List<String> cart) { cart.add("Free bag"); }
static void replace(java.util.List<String> cart) { cart = new java.util.ArrayList<>(); }

int pay = 30000;
addBonus(pay);
System.out.println(pay);        // 30000: the int was copied

var cart = new java.util.ArrayList<String>(java.util.List.of("Shoes"));
addItem(cart);
System.out.println(cart);       // [Shoes, Free bag]: same object changed
replace(cart);
System.out.println(cart);       // [Shoes, Free bag]: caller's variable still points to the old list

Overloading

Several methods can share a name if their parameter lists differ in number or types. The compiler picks the best match from the arguments. A different return type alone is NOT enough.

java
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 double add(int a, int b) { … }   // compile error: same signature as the first

Scope

Parameters and variables declared inside a method (or inside a block) exist only there. Two methods can both have a variable called total without clashing.

Recursion basics

java
static long factorial(int n) {
    if (n <= 1) return 1;          // base case
    return n * factorial(n - 1);   // recursive case
}
// factorial(5) = 120. Without a base case: java.lang.StackOverflowError
Careful: Using == to compare a method's String result, forgetting to use the returned value (calling withGst(100, 18); and ignoring the result), and missing a return on one branch are the classic method mistakes. Read compiler errors such as "missing return statement"; they point exactly at the problem.
Think of it like this: Passing an object to a method is like giving a friend a photocopy of your house key, not the house. They can rearrange the furniture inside (change the object), but if they throw their key copy away and get a key to another house, your key still opens your house.
Tip: Aim for methods that fit on one screen and do one thing. If a method needs a comment saying "Step 1… Step 2…", each step is probably its own method.

Need help?

Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.

Try:

Watch the lesson

Methods: parameters, return values and overloading · 1/6

Methods

In this lesson you will write your own methods.

Prefer a video by a teacher? Find free videos on “java methods parameters return overloading pass by value” on YouTube ↗

In real life: A salary slip calculator

A payroll program for a small firm splits the work into methods: gross pay, provident fund deduction, professional tax, and net pay. Each is easy to check on its own. (Rates simplified for learning; real PF and tax rules have more conditions.)

java
static double gross(double basic, double hra) { return basic + hra; }
static double pf(double basic) { return Math.round(basic * 0.12); }
static double net(double basic, double hra, double professionalTax) {
    return gross(basic, hra) - pf(basic) - professionalTax;
}
// net(30000, 12000, 200) → 42000 - 3600 - 200 = 38200.0

Practice (0/3 done)

Task 1 · Question

What does this print? static void change(int[] a, int b) { a[0] = 99; b = 99; } … int[] arr = {1, 2}; int x = 1; change(arr, x); System.out.println(arr[0] + " " + x);

Task 2 · Question

Which pair of methods can NOT exist together in one class?

Task 3 · Practice

Write a class Emi with static double emi(double principal, double annualRatePercent, int months) using the formula EMI = P × r × (1 + r)^n / ((1 + r)^n − 1), where r is the monthly rate (annual / 12 / 100). Handle r = 0 by returning P / n. Print the EMI for ₹5,00,000 at 9% for 60 months, formatted to 2 decimals.

Quick quiz

Question 1

1.What does void mean in a method declaration?

Question 2

2.Is Java pass-by-value or pass-by-reference?

Question 3

3.What does a method signature consist of?

Question 4

4.Deep recursion without a base case throws…

Read more (free)

Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.

What does void mean in a method declaration?

Answer: The method returns no value

void methods do not return a value.

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

Answer: Always pass-by-value (references are copied for objects)

Java copies every argument; for objects, the copy is the reference.

What does a method signature consist of?

Answer: Name and parameter types

The return type is not part of the signature for overloading.

Deep recursion without a base case throws…

Answer: StackOverflowError

Each call uses stack space until it runs out.

Can you overload two methods that differ only in return type?Related

Answer: No, the parameter lists must differ

The compiler chooses an overload by arguments, so return type alone is not enough (CS0111).

From Parameters in depth: optional, named, ref, out, params, overloading

When does the compiler choose which overload to call?Related

Answer: At compile time, from the argument types

Overload resolution happens while compiling, based on the arguments in each call.

From Overloading, default arguments and recursion

A variable declared inside a method can be used...Related

Answer: Only inside that method (its scope)

Local variables exist only inside the method that declares them.

From Methods: write once, use many times

When does Java add a default no-argument constructor?Related

Answer: Only when the class declares no constructor at all

Writing any constructor removes the default one.

From Constructors and this

Pass the quiz (60% or more) or mark this topic as done when you are ready.

Your progress is saved on this device only.

Next steps

  1. 1 more topic in “Control flow and methods” before its exam: Reading errors and debugging.
  2. Module 2 exam: Control flow and methods · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
  3. Then the next module, Arrays and strings. 60 topics left in the course before the final exam.

← Previous: Loops: for, while, do-while and for-each