Part 05 / Topic 1 of 7
Defining and calling a static method
A method is a named block of code. You define it once and call (run) it as many times as you like. Think of a bill counter at Asha's shop in Pune: you hand over the price and quantity (the parameters), the counter works it out (the call), and hands back a total (the return value).
A method needs: an access word, static, a return type (or void), a name, and parameters in ( ).
static double billTotal(double price, int quantity) {
return price * quantity;
}
return sends a value back to the line that called the method (the caller). System.out.println only shows text on the screen; it gives nothing back. A method declared void has no return value at all — writing return someValue; inside a void method does not compile.
Real-world example: a bill counter at Asha's Store.
double total = billTotal(120.0, 3);
System.out.println(total); // 360.0
System.out.println(total + 40); // 400.0
printBill(120.0, 3); // prints 360.0, gives nothing back
// double x = printBill(120.0, 3); // would NOT compile: void has no value
static double billTotal(double price, int quantity) {
return price * quantity;
}
static void printBill(double price, int quantity) {
System.out.println(price * quantity);
}
return |
System.out.println |
|
|---|---|---|
| What it does | Sends a value back to the caller | Shows text on the screen |
| Can you store the result? | Yes | No (there is nothing to store) |
| Ends the method? | Yes, immediately | No |
🔍 Going deeper:
mainitself is astaticmethod —public static void main(String[] args)— which is why every other method in this part can also bestaticand callmain's helpers directly, without creating an object first.
Full program: examples/01_method_basics.java.
Done here? The practice set for Part 5 — including the solutions — is on the part page.