Free for students · Ad-free · WCAG 2.1 AA Compliant · Accessibility

Method Signatures

Lesson ~10 min read 8 MCQs

In simple terms: In simple terms, method signatures are like unique ID cards for code commands, telling Java exactly which command to run based on its name and the type of information you give it.

Why this matters

Imagine you're ordering a smoothie in downtown Chicago. You walk up to the counter and say, "I'd like a smoothie." The person at the counter, Carlos, will probably ask, "Okay... which one? And what size?"

Just saying "smoothie" isn't enough. You need to be more specific: "I'd like a strawberry banana smoothie, large." That's the information Carlos needs to get you the right drink.

Calling a method in Java is a lot like this. You can't just tell the computer to calculate. You have to tell it what to calculate and give it the numbers it needs. A method's "signature" is its unique name combined with the specific inputs it expects. Understanding this is the key to making your programs actually do things. Today, we'll break down exactly how to read these signatures and call methods correctly.

Calling a method is like ordering a smoothie: specific inputs lead to specific outcomes.

Concept overview

flowchart TD
    A[Start of main method] --> B{int x = 5;};
    B --> C[System.out.println("Before call, x is " + x)];
    C --> D(Call myMethod(x));
    D --> E[main method pauses];
    subgraph myMethod
        F[myMethod starts, parameter 'num' gets a copy of x's value (5)]
        F --> G{num = num + 10; // num is now 15};
        G --> H[System.out.println("Inside method, num is " + num)];
        H --> I[Method ends, returns to caller];
    end
    E --> F;
    I --> J[main method resumes];
    J --> K[System.out.println("After call, x is still " + x)];
    K --> L[End of main method];
This flowchart illustrates the concept of "call by value" and program flow when a method is called. The diagram shows the main program flow being interrupted to execute a method, which works on a copy of the original data, and then control returns to the main program, where the original data remains unchanged.

Core explanation

Hello everyone! It's Saavi. Let's dive into one of the most fundamental building blocks of programming: methods. If variables are the nouns of our programs (the data), then methods are the verbs (the actions).

What is a Method?

Think of a method as a named recipe. It's a block of code that performs a specific task, and you can "call" it by name whenever you need that task done.

For example, you don't need to know the complex engineering inside a microwave to use it. You just put your food in, press the start button, and trust that it will do its job. This is a concept we call procedural abstraction. It lets you use a tool (a method) by knowing what it does, without needing to worry about how it does it.

In Java, a method is a block of code enclosed in braces {} that's given a name.

// This is a simple method definition
public void printWelcomeMessage() {
  System.out.println("Welcome to Shrutam US!");
}

You can call this method anytime you want to print that specific welcome message, without having to type it out again.

The Method Signature: A Unique ID

How does Java know which method you want to run, especially if some have similar names? It uses the method signature.

A method signature has two parts:

The two parts of a method signature: name and parameter types.
  1. The method's name (e.g., printWelcomeMessage)
  2. The ordered list of its parameter types inside the parentheses ()

A parameter is a special variable that acts as a placeholder for a piece of information the method needs to do its job.

Look at this method:

public void displayScore(String playerName, int score) {
  // method body code goes here
}

The signature for this method is displayScore(String, int). It's the name displayScore plus the fact that it needs a String first, and then an int. The order matters!

If a method doesn't need any outside information, its parameter list is empty, like our printWelcomeMessage() method earlier. Its signature is just printWelcomeMessage().

Calling Methods: Giving the Commands

Now that we know how to identify a method, how do we actually use it? We call it.

A method call is a statement that tells the program to pause what it's doing, jump to the method's code, execute it, and then come back.

When you call a method, you provide arguments, which are the actual values that fill in the parameter placeholders.

Tracing a method call: arguments fill parameters, then the method executes.
// In your main program...

// Calling a method with no parameters
printWelcomeMessage();

// Calling a method with parameters
String player = "Maya";
int currentScore = 1500;
displayScore(player, currentScore); // "Maya" and 1500 are the arguments

displayScore(1500, "Maya"); would cause an error!

When you pass an argument, Java uses call by value. This means the method receives a copy of the argument's value. If the method changes its parameter's value, the original variable you passed in is not affected. Think of it like giving someone a photocopy of a document—they can write on their copy all they want, but your original remains untouched.

Void vs. Non-Void: Does it Give Anything Back?

Methods come in two flavors, based on what they give back to you after they run.

  1. void Methods: These methods perform an action but do not return any value. The keyword void in the method definition means "returns nothing." Our printWelcomeMessage() and displayScore() methods are void. You call them on a line by themselves to get a job done.

    // Correct way to call a void method
    displayScore("Jordan", 95);
  2. Non-void Methods: These methods perform a task and then return a single piece of data back to the spot where they were called. The type of data they return is specified in place of void.

    // This method calculates sales tax and returns it
    public double calculateSalesTax(double price) {
      double taxRate = 0.0825; // Let's use Dallas's tax rate
      double taxAmount = price * taxRate;
      return taxAmount; // Returns a double value
    }

    Because this method returns a value, you have to do something with that value. You can't just call it on its own line. You must either store it in a variable or use it directly in another expression.

    // Store the returned value in a variable
    double itemPrice = 29.99;
    double tax = calculateSalesTax(itemPrice); // The value returned by the method is stored in 'tax'
    double totalPrice = itemPrice + tax;
    System.out.println("Total: $" + totalPrice);
    
    // Or use it directly
    System.out.println("Total: $" + (itemPrice + calculateSalesTax(itemPrice)));

Method Overloading: Same Name, Different Job

What if you want to have methods with the same name but have them do slightly different things based on the input? This is called method overloading.

Java allows you to define multiple methods with the same name, as long as their signatures are different. This means they must have a different number of parameters or different types of parameters.

Imagine a drawShape method:

public void drawShape(int sideLength) {
  // Code to draw a square
}

public void drawShape(int width, int height) {
  // Code to draw a rectangle
}

public void drawShape(double radius) {
  // Code to draw a circle
}

When you call drawShape, Java looks at the arguments you provide to figure out which version to run.

  • drawShape(5); calls the square version.
  • drawShape(5, 10); calls the rectangle version.
  • drawShape(7.5); calls the circle version.

This makes your code more intuitive and readable. Instead of drawSquare, drawRectangle, drawCircle, you just have one logical action: drawShape.

See it in action

python
Line 1
Output
Click Run to see the output.

        
Try these
    © Shrutam.ai

    Worked examples

    Let's walk through a few examples together. The key is to read the method signatures carefully to know exactly what they need and what they give back.

    Example 1: Calling a void Method

    Problem: You are given a Robot class with a method to greet a user. The documentation for the method looks like this:

    public void greetUser(String userName)

    • Description: Prints a personalized greeting to the console.
    • Parameters: userName - The name of the user to greet.

    How would you make a Robot object named sparky greet a user named "Priya"?

    Solution Walkthrough:

    1. 1
      Analyze the Signature
      The method is named greetUser. It's public and void. void is our big clue: this method performs an action but doesn't return any data we need to catch. The parameter list is (String userName), so it requires exactly one argument: a String.
    2. 2
      Create the Object
      First, we need an instance of the Robot class to call the method on.
      Robot sparky = new Robot();
    3. 3
      Prepare the Argument
      The method needs a String for the user's name. The problem specifies the name is "Priya".
      String name = "Priya";
    4. 4
      Call the Method
      Now, we call the greetUser method on our object (sparky) and pass the name variable as the argument.
      sparky.greetUser(name);

      Alternatively, you could pass the string literal directly:

      sparky.greetUser("Priya");

      Both are correct! The program will pause, execute the greetUser method (which prints something like "Hello, Priya!"), and then continue.

    Example 2: Using a Non-void Method

    Problem: You have a Game class with a method to check if a player's score is a new high score.

    public boolean isHighScore(int score)

    • Description: Compares the given score to the current high score.
    • Parameters: score - The player's score to check.
    • Returns: true if the score is a new high score, false otherwise.

    A player, Marcus, just scored 12,500 points. Write the code to call this method on a Game object named nba2k and print a message only if it's a new high score.

    Solution Walkthrough:

    1. 1
      Analyze the Signature
      The method is isHighScore. The return type is boolean—this is critical! It means the method will give us back a true or false value. It expects one int argument.
    2. 2
      Create the Object and Data
      Game nba2k = new Game();
      int marcusScore = 12500;
    3. 3
      Call the Method and Store the Result
      Since the method returns a boolean, we must capture that value to use it. The most readable way is to store it in a variable.
      boolean newRecord = nba2k.isHighScore(marcusScore);

      After this line runs, the newRecord variable will hold either true or false.

    4. 4
      Use the Result
      Now we can use that boolean variable to make a decision.
      if (newRecord == true) { // Or more simply: if (newRecord)
        System.out.println("Congratulations, Marcus! New high score!");
      }

      We only print the message if the method returned true. We successfully used the output of the method to control the flow of our program.

    The difference between calling a `void` method and a non-`void` method.

    Try it yourself

    Time to put this into practice. Don't worry about writing the full class, just focus on the method calls.

    1. 1
      Ticket Machine Challenge
      You have a TicketMachine class with the following two overloaded methods:
      • public void printTicket(String eventName)
      • public void printTicket(String eventName, int seatNumber)

      Write two separate lines of code. First, call the method to print a general admission ticket for a "Seattle Sounders Game". Second, call the method to print a ticket for the same game but for seat number 112.

      Hint: Java will choose which version of printTicket to run based on the number of arguments you provide.

    2. 2
      Discount Calculator
      You have a Store class with this method:
      • public double getFinalPrice(double originalPrice, double discountPercentage)
      • Returns: The final price after the discount is applied.

      A jacket costs $89.50 and has a 15% discount (which you should represent as 0.15). Write the code to call this method and then print the final price to the console in a user-friendly format, like "Your final price is $XX.XX".

      Hint: This is a non-void method. What do you need to do with the value it gives you back?

    Overloaded methods share a name but have different signatures.