Methods in Java

Naveen AnamaneniUpdated · 4 min read

A restaurant kitchen doesn't write out how to make dal from scratch on every order. There's one recipe, with a name, and the cook just "makes dal" whenever it's ordered, with a different number of servings each time. A method is a recipe in your code: a block of statements with a name, which you write once and call whenever you need it, giving it different inputs each time.

The Parts of a Method

Return type, name, parameters, body
Fare.java▶ Try it
public class Fare {
    static int totalFare(int perPerson, int people) {
        return perPerson * people;
    }
 
    public static void main(String[] args) {
        int family = totalFare(450, 4);
        int couple = totalFare(450, 2);
        System.out.println("Family: Rs. " + family);
        System.out.println("Couple: Rs. " + couple);
    }
}
Output
Family: Rs. 1800
Couple: Rs. 900

How it works

  1. Lines 2 to 4 declare the method totalFare. It takes two ints and gives back an int.
  2. Line 7 calls it with the arguments 450 and 4. Inside the method, perPerson is 450 and people is 4.
  3. return sends back 1800, which is stored in family.
  4. Line 8 calls the same method again with different arguments. The calculation is written once and used twice.

Try it yourself: add a third call for a group of 7, and print the result.

void Methods: Doing, Not Answering

Some methods do something, such as printing, and give nothing back. Their return type is void:

Receipt.java▶ Try it
public class Receipt {
    static void printLine(String item, int price) {
        String dots = ".".repeat(16 - item.length());
        System.out.println(item + dots + " Rs. " + price);
    }
 
    public static void main(String[] args) {
        printLine("Rice", 340);
        printLine("Toor dal", 165);
        printLine("Oil", 190);
    }
}
Output
Rice............ Rs. 340
Toor dal........ Rs. 165
Oil............. Rs. 190

The formatting logic lives in one place. To change the receipt's look, you change one method, not every line that prints an item.

Why Write Methods

Without methodsWith methods
The same calculation copied in five placesWritten once, called five times
A bug fix must be made five timesFixed once
main is 200 lines longmain reads like a list of steps
Hard to test one partEach method can be tested on its own (testing is covered later in the course)

Common Mistakes

Declaring a method inside another method. Methods sit directly inside the class, side by side with main.

Forgetting return in a non-void method. The compiler reports missing return statement.

Calling with the wrong number or types of arguments. totalFare(450) doesn't compile: the method needs two ints.

Interview Corner

What is the difference between a parameter and an argument?

A parameter is the variable in the method's declaration, such as int people. An argument is the actual value passed when calling it, such as 4 in totalFare(450, 4).

What does void mean?

The method doesn't return a value. It's called for what it does, such as printing or changing data, and can use a bare return; to finish early.

Practice

  1. Easy: Write static int square(int n) and print the squares of 1 to 5 by calling it in a loop.
  2. Harder: Write static boolean isLeapYear(int year) (divisible by 4, but not by 100 unless also by 400) and test it with 1900, 2000 and 2024.

Quick check: Methods

4 questions
1In static int totalFare(int perPerson, int people), what is int before the name?
2What does a void method return?
3In totalFare(450, 4), what are 450 and 4?
4Where are methods declared?

Key Takeaways

Was this tutorial helpful?

Lesson 81 of 482