Why Methods Matter
As programs grow, repeating the same logic in multiple places makes code harder to read, test, and change. A method is a named block of code you can run (call) whenever you need it. Methods help you organize code into small, focused pieces and reuse them across your program.
In Java, you will often start by calling methods that already exist (built-in methods), then move to writing your own methods to keep your code clean and maintainable.
Calling Built-in Methods
You have already used methods without necessarily naming them as such. For example, printing to the console is done by calling a method. Another common built-in method is converting text to a number.
Example: Using a Built-in Parsing Method
When you have a numeric value stored as text, you can convert it using a built-in method:
String text = "42"; int value = Integer.parseInt(text);Here, parseInt is a method that belongs to the Integer class. You call it using Integer.parseInt(...) and pass the input inside parentheses.
Continue in our app.
You can listen to the audiobook with the screen off, receive a free certificate for this course, and also have access to 5,000 other free online courses.
Or continue reading below...Download the app
What a Method Call Looks Like
A method call generally follows this pattern:
result = something.methodName(argument1, argument2);Some methods return a value (you can store it in a variable). Others perform an action and return nothing.
Method Signatures: Name, Parameters, and Return Type
When you create your own methods, you define a method signature. In beginner-friendly terms, the signature describes how the method is called: its name and the types and order of its parameters. The method definition also includes a return type.
A typical method definition looks like this:
public static returnType methodName(type1 param1, type2 param2) { // code return someValue; }- methodName: a descriptive verb-style name, like
calculateTotal. - parameters: inputs the method needs, listed inside parentheses.
- returnType: the type of value the method gives back (for example
int,double,String), orvoidif it returns nothing.
Writing Your First Custom Method: calculateTotal(price, quantity)
Suppose you need to compute a total cost in several places. Instead of repeating the multiplication each time, create a method.
Step-by-step
- Step 1: Decide inputs: price and quantity.
- Step 2: Decide output: total cost, likely a
double. - Step 3: Write the method with parameters and a return statement.
- Step 4: Call the method from
mainand use the returned value.
public class Main { public static void main(String[] args) { double total1 = calculateTotal(9.99, 3); double total2 = calculateTotal(2.50, 10); System.out.println("Total 1: " + total1); System.out.println("Total 2: " + total2); } public static double calculateTotal(double price, int quantity) { return price * quantity; } }Notice the method call: calculateTotal(9.99, 3). The values you pass are called arguments. They must match the parameter types and order: first a double, then an int.
Return Types and the return Statement
A method with a non-void return type must return a value of that type on every possible path through the method.
Examples of return types:
int: return whole numbersdouble: return decimal valuesboolean: returntrueorfalseString: return text
Boolean Methods: isEven(number)
Methods that return boolean are great for checks and validations. A classic example is checking whether a number is even.
public class Main { public static void main(String[] args) { System.out.println(isEven(10)); // true System.out.println(isEven(7)); // false } public static boolean isEven(int number) { return number % 2 == 0; } }This method returns the result of a condition directly. Because the expression number % 2 == 0 is already a boolean, you can return it without extra if statements.
String-returning Methods: formatGreeting(name)
Methods can build and return strings, which is useful for formatting output consistently.
public class Main { public static void main(String[] args) { String message = formatGreeting("Amina"); System.out.println(message); } public static String formatGreeting(String name) { return "Hello, " + name + "! Welcome."; } }This keeps formatting logic in one place. If you later want to change the greeting style, you update the method once instead of searching through your whole program.
Void Methods: Doing Work Without Returning a Value
Some methods perform an action rather than producing a value. These methods use the return type void.
Example: Printing a Receipt Line
public class Main { public static void main(String[] args) { printLineItem("Notebook", 3.25, 2); } public static void printLineItem(String itemName, double price, int quantity) { double total = price * quantity; System.out.println(itemName + " x" + quantity + " = " + total); } }A void method can still use return; to exit early, but it cannot return a value.
Parameters, Arguments, and Common Mistakes
Matching Types and Order
Parameters are defined in the method, arguments are passed in the call. Java matches them by position.
// Method expects (double, int) public static double calculateTotal(double price, int quantity) { return price * quantity; } // Correct call: calculateTotal(4.50, 2) // Incorrect call: calculateTotal(2, 4.50) // wrong order and typesScope: Variables Inside Methods Stay Inside
Variables declared inside a method are local to that method. You cannot use them outside it.
public static void example() { int x = 5; } // x is not accessible hereIf you need a value outside the method, return it (or store it somewhere appropriate).
Breaking a Larger Program into Smaller Methods
A good way to design a program is to identify repeated tasks or distinct responsibilities and turn them into methods. Aim for methods that do one clear job.
Example: Small Checkout Program Organized with Methods
This example uses multiple methods together: one to compute totals, one to format a greeting, one to check a condition, and one to print a line item.
public class Main { public static void main(String[] args) { System.out.println(formatGreeting("Sam")); double price = 4.99; int quantity = 6; printLineItem("Pen", price, quantity); double total = calculateTotal(price, quantity); System.out.println("Total: " + total); if (isEven(quantity)) { System.out.println("You bought an even number of items."); } else { System.out.println("You bought an odd number of items."); } } public static String formatGreeting(String name) { return "Hello, " + name + "!"; } public static double calculateTotal(double price, int quantity) { return price * quantity; } public static boolean isEven(int number) { return number % 2 == 0; } public static void printLineItem(String itemName, double price, int quantity) { System.out.println(itemName + " x" + quantity + " = " + calculateTotal(price, quantity)); } }Notice how printLineItem reuses calculateTotal instead of duplicating the multiplication. This is a key benefit of methods: methods can call other methods.
Testing Methods: Quick, Practical Checks
When you write a method, test it with a few different inputs to confirm it behaves correctly. A simple approach is to call the method from main with known values and print the results.
Example Test Cases
System.out.println(calculateTotal(10.0, 0)); // expect 0.0 System.out.println(calculateTotal(1.5, 4)); // expect 6.0 System.out.println(isEven(0)); // true System.out.println(isEven(-2)); // true System.out.println(isEven(-3)); // false System.out.println(formatGreeting("Lee")); // Hello, Lee!If a result surprises you, check parameter types, the order of arguments, and the logic inside the method.
Practice Exercises
1) Write and Call Basic Methods
- Create
public static int square(int n)that returnsn * n. Call it with at least three values and print the results. - Create
public static boolean isPositive(int n)that returnstrueifnis greater than 0. Test with negative, zero, and positive values.
2) Build a Mini Price Calculator with Multiple Methods
Write a program that uses these methods together:
public static double calculateTotal(double price, int quantity)public static double applyDiscount(double total, double discountRate)wherediscountRateis something like0.10for 10%public static void printSummary(String itemName, double price, int quantity, double finalTotal)
In main, choose values for item name, price, quantity, and discount rate. Compute the total, apply the discount, then print a summary using printSummary.
3) Combine String Formatting and Checks
- Write
public static String formatGreeting(String name)that returns a greeting. - Write
public static boolean isEven(int number). - In
main, callformatGreetingand print it, then read or set a number and print whether it is even usingisEven.
4) Refactor a Single Long main into Methods
Start with a main that does all of these steps inline: compute two totals for two different items, print each line item, then print a grand total. Refactor it so that:
- Each line item is printed by a
voidmethod. - Each total is computed by
calculateTotal. - The grand total is computed by a method
public static double calculateGrandTotal(double total1, double total2).