Beginner · Control flow and methods · topic 9 of 60 · 30 min
Methods: parameters, return values and overloading
Explanation
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.
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.
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 listOverloading
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.
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 firstScope
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
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.StackOverflowErrorNeed 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
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.)
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.0Practice (0/3 done)
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);
Which pair of methods can NOT exist together in one class?
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
Read more (free)
Related help
Before this, learn
This topic builds on these. If something here feels new, open them first.
Related topics
- Reading errors and debuggingControl flow and methods · same module
- switch statements and switch expressionsControl flow and methods · same module
- Parameters in depth: optional, named, ref, out, params, overloadingC# and .NET · Decisions, loops and methods
- Overloading, default arguments and recursionC++ Programming (modern C++ and DSA) · Decisions, loops and functions
- Methods: write once, use many timesC# and .NET · Decisions, loops and methods
- Constructors and thisClasses and objects
Questions people ask about this
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.
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.
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.
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 more topic in “Control flow and methods” before its exam: Reading errors and debugging.
- Module 2 exam: Control flow and methods · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
- Then the next module, Arrays and strings. 60 topics left in the course before the final exam.