Part 05 / Stage 1
Methods
Goal: Write your own reusable
staticmethods with clear parameters and return types, overload them, use varargs, understand scope, and write a simple recursive method. Time: ~5 hours
What you will learn
- Defining and calling a
staticmethod; parameters and return types voidvs.return(and whyreturnis notSystem.out.println)- Method overloading: same name, different parameter lists
- Varargs (
...): any number of arguments of one type - Scope: local variables, parameter scope, block scope, and class-level constants
- Why a method's local variables do not remember anything between calls
- Recursion: base case, a smaller problem, and
StackOverflowError
Every method here is static, written inside one class, and called from main. That is deliberate for this stage (see Part 1–4): no objects of your own yet, so every method belongs to the class itself, not to an instance. Stage 2 explains what static really means once real objects exist.
Topics in this part
Practice
Write each answer as one class ExNN (saved as solutions/exNN.java, matching the stage-wide convention — see solutions/ex01.java) with a public static void main(String[] args) and the helper methods it needs, exactly like the examples. Compile with javac and run with java, matching the sample output. These seven exercises build up, piece by piece, to the discount calculator Part 5 asks you to build.
Exercise 1: Store greeting
Scenario: Asha's Store, Pune wants a welcome message and a per-customer greeting printed at the counter.
What to do: Write printWelcome() (void, prints Welcome to Asha's Store, Pune) and greetCustomer(String name) (returns a String, does not print). Call printWelcome() once, then print greetCustomer("Ravi") and greetCustomer("Meera").
Sample output:
Welcome to Asha's Store, Pune
Hello, Ravi! Thanks for shopping with us.
Hello, Meera! Thanks for shopping with us.
💡 Hint: greetCustomer should return "Hello, " + name + "! Thanks for shopping with us."; — the caller decides to print it, the method just hands back the String.
Exercise 2: Overloaded discounted price
Scenario: Some sales are a straight percentage off; others stack a flat amount off on top.
What to do: Write discountedPrice(double price, double percentOff) (percentage off, rounded to 2 decimals) and an overload discountedPrice(double price, double percentOff, double flatOff) (percentage off, then the flat amount off, never below 0). Print discountedPrice(1500.0, 10.0), discountedPrice(1500.0, 10.0, 200.0), and discountedPrice(100.0, 10.0, 200.0).
Sample output:
1350.0
1150.0
0.0
💡 Hint: Round with Math.round(value * 100) / 100.0. The three-parameter overload can call the two-parameter one: discountedPrice(price, percentOff) first, then subtract flatOff with Math.max(..., 0).
Exercise 3: Varargs basket tools
Scenario: A basket can hold any number of items — including none.
What to do: Write basketTotal(double... prices) (sum of all prices, 0 for an empty basket) and mostExpensive(double... prices) (the highest price, 0 for an empty basket). Print basketTotal(), basketTotal(199.0), basketTotal(199.0, 349.0, 90.0), then mostExpensive() and mostExpensive(199.0, 349.0, 90.0).
Sample output:
0.0
199.0
638.0
0.0
349.0
💡 Hint: Inside the method, prices is a plain double[] — loop over it with for (double price : prices), and check prices.length == 0 for the empty case.
Exercise 4: A packaging fee constant and a fresh-every-call counter
Scenario: Every order gets a fixed packaging fee. The shop also hands out a token number at the counter — and each visit should start counting from scratch, not remember the last customer.
What to do: Declare static final double PACKAGING_FEE = 15.0; at the top of the class. Write addPackaging(double price) that returns price + PACKAGING_FEE. Write nextTokenNumber() that declares a local int token = 0;, increments it once, and returns it. Print addPackaging(500.0), addPackaging(1200.0), then nextTokenNumber() twice.
Sample output:
515.0
1215.0
1
1
💡 Hint: The second nextTokenNumber() call also prints 1, not 2 — token is declared fresh inside the method every time, so nothing is remembered between calls. Only PACKAGING_FEE, declared static final at class level, is shared.
Exercise 5: Recursive savings growth and digit count
Scenario: A savings scheme compounds a fixed interest rate every year. Separately, a form needs to know how many digits long an account number is. What to do:
- Write a recursive
savingsGrowth(double principal, double ratePercent, int years): base caseyears == 0returns the principal (rounded to 2 decimals); otherwise grow the principal byratePercentonce and recurse withyears - 1. - Write a recursive
countDigits(int n)that returns how many digits a positive whole number has, without converting it to aString. Base case: a number below10has exactly one digit.
Print savingsGrowth(10000.0, 8.0, 0), savingsGrowth(10000.0, 8.0, 3), countDigits(560001), countDigits(7).
Sample output:
10000.0
12597.12
6
1
💡 Hint: countDigits: the recursive case is 1 + countDigits(n / 10) — integer division n / 10 drops the last digit each time.
Exercise 6: Overloads + varargs + a shared GST constant
Scenario: Asha's Store wants one finalPrice name that works whether there is no discount, a percentage discount, or a percentage discount plus the "FESTIVE50" coupon (₹50 off) — and a way to price a whole basket in one call.
What to do: Declare static final double GST_RATE = 0.18;. Write three overloads of finalPrice:
finalPrice(double price)— GST only.finalPrice(double price, double percentOff)— percentage off, then GST.finalPrice(double price, double percentOff, String couponCode)— percentage off, then"FESTIVE50"takes ₹50 more off (never below0), then GST.
Then write basketFinalPrice(double percentOff, double... prices) (a normal parameter before the varargs parameter) that sums prices and calls the two-parameter finalPrice overload on the total.
Print finalPrice(2000.0), finalPrice(2000.0, 15.0), finalPrice(2000.0, 15.0, "FESTIVE50"), basketFinalPrice(15.0, 500.0, 700.0, 800.0).
Sample output:
2360.0
2006.0
1947.0
2006.0
💡 Hint: basketFinalPrice's basket (500 + 700 + 800 = 2000) matches the second line exactly, because it calls the same two-parameter finalPrice on the same total — round-trip it to check your overloads agree with each other.
Exercise 7: The discount calculator
Scenario: Put it all together into the discount calculator this part set out to build: a receipt for Asha's Store, Pune, covering a basket of items, a multi-year loyalty discount, a seasonal percentage discount stacked with one coupon, and GST. What to do:
- Store
itemNamesanditemPricesas parallel arrays (Part 4):{"Rice 5kg", "Dal 1kg", "Ghee 500ml", "Sugar 1kg"}and{450.0, 120.0, 650.0, 55.0}. - Print the header
Asha's Store, Pune - Receipt, then each item as<name> - ₹<price>. - Write a varargs
totalBill(double... prices)and print the basket total. - Write a recursive
loyaltyPrice(double price, double percentOff, int yearsLeft)(base caseyearsLeft == 0) that compounds a 5% loyalty discount for 2 years on the basket total, and print the result. - Reuse the three
finalPriceoverloads from Exercise 6's idea (price only / + percent / + percent + coupon) withGST_RATE = 0.18, to apply a 12% seasonal discount plus the"SAVE100"coupon (flat ₹100 off) on top of the loyalty price, and print the final payable amount.
Sample output:
Asha's Store, Pune - Receipt
Rice 5kg - ₹450.0
Dal 1kg - ₹120.0
Ghee 500ml - ₹650.0
Sugar 1kg - ₹55.0
Basket total: ₹1275.0
After loyalty discount: ₹1150.69
Payable (with GST): ₹1076.88
💡 Hint: Round every money value with Math.round(value * 100) / 100.0 right before you return it, so each step's output matches exactly. Build and test totalBill, loyaltyPrice and the finalPrice overloads one at a time before wiring them together in main.
Show the solutions for Part 5 (7 files)
solutions/ex01.java
/*
* Exercise 1: Store greeting
*
* Run:
* javac ex01.java -d /tmp/out
* java -cp /tmp/out Ex01
*/
class Ex01 {
public static void main(String[] args) {
printWelcome();
System.out.println(greetCustomer("Ravi"));
System.out.println(greetCustomer("Meera"));
}
static void printWelcome() {
System.out.println("Welcome to Asha's Store, Pune");
}
static String greetCustomer(String name) {
return "Hello, " + name + "! Thanks for shopping with us.";
}
}
solutions/ex02.java
/*
* Exercise 2: Overloaded discounted price
*
* Run:
* javac ex02.java -d /tmp/out
* java -cp /tmp/out Ex02
*/
class Ex02 {
public static void main(String[] args) {
System.out.println(discountedPrice(1500.0, 10.0));
System.out.println(discountedPrice(1500.0, 10.0, 200.0));
System.out.println(discountedPrice(100.0, 10.0, 200.0)); // never below 0
}
// Percentage discount only.
static double discountedPrice(double price, double percentOff) {
return round2(price - (price * percentOff / 100));
}
// Overload: percentage discount, then a flat amount off, never below 0.
static double discountedPrice(double price, double percentOff, double flatOff) {
double afterPercent = discountedPrice(price, percentOff);
return round2(Math.max(afterPercent - flatOff, 0));
}
static double round2(double value) {
return Math.round(value * 100) / 100.0;
}
}
solutions/ex03.java
/*
* Exercise 3: Varargs basket tools
*
* Run:
* javac ex03.java -d /tmp/out
* java -cp /tmp/out Ex03
*/
class Ex03 {
public static void main(String[] args) {
System.out.println(basketTotal()); // empty basket
System.out.println(basketTotal(199.0)); // one item
System.out.println(basketTotal(199.0, 349.0, 90.0)); // three items
System.out.println(mostExpensive()); // empty basket -> 0.0
System.out.println(mostExpensive(199.0, 349.0, 90.0)); // 349.0
}
static double basketTotal(double... prices) {
double total = 0;
for (double price : prices) {
total += price;
}
return total;
}
static double mostExpensive(double... prices) {
if (prices.length == 0) {
return 0;
}
double max = prices[0];
for (double price : prices) {
if (price > max) {
max = price;
}
}
return max;
}
}
solutions/ex04.java
/*
* Exercise 4: Packaging fee constant and a fresh-every-call counter
*
* Run:
* javac ex04.java -d /tmp/out
* java -cp /tmp/out Ex04
*/
class Ex04 {
static final double PACKAGING_FEE = 15.0;
public static void main(String[] args) {
System.out.println(addPackaging(500.0));
System.out.println(addPackaging(1200.0));
System.out.println(nextTokenNumber()); // 1
System.out.println(nextTokenNumber()); // 1 again, not 2
}
static double addPackaging(double price) {
return price + PACKAGING_FEE;
}
static int nextTokenNumber() {
int token = 0; // fresh on every call
token++;
return token;
}
}
solutions/ex05.java
/*
* Exercise 5: Recursive savings growth and digit count
*
* Run:
* javac ex05.java -d /tmp/out
* java -cp /tmp/out Ex05
*/
class Ex05 {
public static void main(String[] args) {
System.out.println(savingsGrowth(10000.0, 8.0, 0)); // 10000.0
System.out.println(savingsGrowth(10000.0, 8.0, 3)); // 12597.12
System.out.println(countDigits(560001)); // 6
System.out.println(countDigits(7)); // 1
}
// Base case: 0 years left -> principal does not grow any further.
static double savingsGrowth(double principal, double ratePercent, int years) {
if (years == 0) {
return round2(principal);
}
double grown = principal * (1 + ratePercent / 100);
return savingsGrowth(grown, ratePercent, years - 1);
}
// Base case: a number below 10 has exactly one digit.
// No String conversion: peel off the last digit with % and / each time.
static int countDigits(int n) {
if (n < 10) {
return 1;
}
return 1 + countDigits(n / 10);
}
static double round2(double value) {
return Math.round(value * 100) / 100.0;
}
}
solutions/ex06.java
/*
* Exercise 6: Overloads + varargs + a shared GST constant
*
* Run:
* javac ex06.java -d /tmp/out
* java -cp /tmp/out Ex06
*/
class Ex06 {
static final double GST_RATE = 0.18;
public static void main(String[] args) {
System.out.println(finalPrice(2000.0));
System.out.println(finalPrice(2000.0, 15.0));
System.out.println(finalPrice(2000.0, 15.0, "FESTIVE50"));
System.out.println(basketFinalPrice(15.0, 500.0, 700.0, 800.0));
}
static double finalPrice(double price) {
return withGst(price);
}
static double finalPrice(double price, double percentOff) {
double discounted = price - (price * percentOff / 100);
return withGst(discounted);
}
static double finalPrice(double price, double percentOff, String couponCode) {
double discounted = price - (price * percentOff / 100);
if ("FESTIVE50".equals(couponCode)) {
discounted = Math.max(discounted - 50, 0);
}
return withGst(discounted);
}
// A normal parameter (percentOff) before the varargs parameter (prices).
static double basketFinalPrice(double percentOff, double... prices) {
double sum = 0;
for (double price : prices) {
sum += price;
}
return finalPrice(sum, percentOff);
}
static double withGst(double price) {
return round2(price * (1 + GST_RATE));
}
static double round2(double value) {
return Math.round(value * 100) / 100.0;
}
}
solutions/ex07.java
/*
* Exercise 7: The discount calculator (the part's "build")
*
* A receipt for Asha's Store, Pune: basket total (varargs), a loyalty
* discount that compounds per year (recursion), a percentage discount
* plus one coupon (overloading), and GST (a shared static final constant).
*
* Run:
* javac ex07.java -d /tmp/out
* java -cp /tmp/out Ex07
*/
class Ex07 {
static final double GST_RATE = 0.18;
public static void main(String[] args) {
String[] itemNames = {"Rice 5kg", "Dal 1kg", "Ghee 500ml", "Sugar 1kg"};
double[] itemPrices = {450.0, 120.0, 650.0, 55.0};
System.out.println("Asha's Store, Pune - Receipt");
for (int i = 0; i < itemNames.length; i++) {
System.out.println(itemNames[i] + " - ₹" + itemPrices[i]);
}
double basketTotal = totalBill(itemPrices[0], itemPrices[1], itemPrices[2], itemPrices[3]);
System.out.println("Basket total: ₹" + basketTotal);
// A 2-year loyalty card, 5% off compounding each year (recursion).
double afterLoyalty = loyaltyPrice(basketTotal, 5.0, 2);
System.out.println("After loyalty discount: ₹" + afterLoyalty);
// 12% seasonal discount, stacked with one coupon (overloading).
double payable = finalPrice(afterLoyalty, 12.0, "SAVE100");
System.out.println("Payable (with GST): ₹" + payable);
}
// Overload 1: no discount, GST only.
static double finalPrice(double price) {
return withGst(price);
}
// Overload 2: a percentage discount, then GST.
static double finalPrice(double price, double percentOff) {
double discounted = price - (price * percentOff / 100);
return withGst(discounted);
}
// Overload 3: a percentage discount, then one flat coupon, then GST.
static double finalPrice(double price, double percentOff, String couponCode) {
double discounted = price - (price * percentOff / 100);
if ("SAVE100".equals(couponCode)) {
discounted = Math.max(discounted - 100, 0);
}
return withGst(discounted);
}
static double withGst(double price) {
return round2(price * (1 + GST_RATE));
}
// Varargs: any number of item prices in one basket.
static double totalBill(double... prices) {
double total = 0;
for (double price : prices) {
total += price;
}
return round2(total);
}
// Recursive: compounds percentOff for each loyalty year left.
static double loyaltyPrice(double price, double percentOff, int yearsLeft) {
if (yearsLeft == 0) { // base case
return round2(price);
}
double afterOneYear = price - (price * percentOff / 100);
return loyaltyPrice(afterOneYear, percentOff, yearsLeft - 1);
}
static double round2(double value) {
return Math.round(value * 100) / 100.0;
}
}
Common mistakes
| Mistake | Why it is wrong | Fix |
|---|---|---|
Writing void and then return someValue; |
A void method has nothing to return |
Change the return type, or drop the value and just return; |
| Expecting a changed parameter to be visible outside | Primitives (int, double, ...) are copied into the method |
return the new value and store it at the call site |
| Two overloads that differ only in return type | The compiler cannot tell calls apart from the return type alone | Give them different parameter lists |
| Varargs parameter not last, or more than one varargs parameter | Does not compile | Put the varargs parameter last, and use only one |
Using a loop or if variable after its { } ends |
It no longer exists in that scope | Declare it outside the block if you need it later, or return it |
Trying to reassign a static final field inside a method |
It is read-only by design | Compute a new value and return/store it separately |
| Forgetting the base case in recursion | It never stops → StackOverflowError |
Always write the stopping condition first, before the recursive call |
| Recursing thousands of levels deep for a simple running total | Wastes stack and time | Use a for/while loop instead |
Quick recap
- A
staticmethod has a return type (orvoid), parameters, and a body;returnsends a value back,System.out.printlndoes not. - Overloading lets several methods share a name if their parameter lists differ; the compiler picks one at compile time from your arguments.
Type... name(varargs) accepts zero or more arguments of one type as an array; it must be the last parameter.- Parameters and local variables live only inside their own method call, or their own block
{ }; nothing is shared between calls unless it is a class-levelstatic finalconstant. - Recursion needs a base case to stop; without one, the call stack fills up and Java throws
StackOverflowError. - The discount calculator combines all of this: overloaded
finalPricemethods, a varargstotalBill, a sharedGST_RATEconstant, and a recursiveloyaltyPrice.
Checklist
- I can write a
staticmethod with parameters and a return type, and explainvoidvs.return. - I can write two or three overloads of the same method name and explain how the compiler picks between them.
- I can write and call a varargs method, including with zero arguments.
- I can explain why a method's local variables do not remember anything between calls.
- I can explain the difference between a local variable, a block-scoped variable and a
static finalconstant. - I can write a recursive method with a correct base case.
- I can explain what happens, and why, when a recursive method has no base case.