Method Signatures
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.
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];
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 method's name (e.g.,
printWelcomeMessage) - 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.
// 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.
-
voidMethods: These methods perform an action but do not return any value. The keywordvoidin the method definition means "returns nothing." OurprintWelcomeMessage()anddisplayScore()methods arevoid. You call them on a line by themselves to get a job done.// Correct way to call a void method displayScore("Jordan", 95); -
Non-
voidMethods: 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 ofvoid.// 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
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:
- 1Analyze the SignatureThe method is named
greetUser. It'spublicandvoid.voidis 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: aString. - 2Create the ObjectFirst, we need an instance of the
Robotclass to call the method on.Robot sparky = new Robot(); - 3Prepare the ArgumentThe method needs a
Stringfor the user's name. The problem specifies the name is "Priya".String name = "Priya"; - 4Call the MethodNow, we call the
greetUsermethod on our object (sparky) and pass thenamevariable 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
greetUsermethod (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:
trueif the score is a new high score,falseotherwise.
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:
- 1Analyze the SignatureThe method is
isHighScore. The return type isboolean—this is critical! It means the method will give us back atrueorfalsevalue. It expects oneintargument. - 2Create the Object and Data
Game nba2k = new Game(); int marcusScore = 12500; - 3Call the Method and Store the ResultSince 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
newRecordvariable will hold eithertrueorfalse. - 4Use the ResultNow 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.
Try it yourself
Time to put this into practice. Don't worry about writing the full class, just focus on the method calls.
- 1Ticket Machine ChallengeYou have a
TicketMachineclass 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
printTicketto run based on the number of arguments you provide. - 2Discount CalculatorYou have a
Storeclass 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-
voidmethod. What do you need to do with the value it gives you back?
Practice — 8 questions
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.
// This is a simple method definition
public void printWelcomeMessage() {
System.out.println("Welcome to Shrutam US!");
}
- 1.9.A: Identify the correct method to call based on documentation and method signatures.
- 1.9.B: Describe how to call methods.
- 1.9.A.1
- A method is a named block of code that only runs when it is called. A block of code is any section of code that is enclosed in braces. Procedural abstraction allows a programmer to use a method by knowing what the method does even if they do not know how the method was written.
- 1.9.A.2
- A parameter is a variable declared in the header of a method or constructor and can be used inside the body of the method. This allows values or arguments to be passed and used by a method or constructor. A method signature for a method with parameters consists of the method name and the ordered list of parameter types. A method signature for a method without parameters consists of the method name and an empty parameter list.
- 1.9.B.1
- A void method does not have a return value and is therefore not called as part of an expression.
- 1.9.B.2
- A non-void method returns a value that is the same type as the return type in the header. To use the return value when calling a non-void method, it must be stored in a variable or used as part of an expression.
- 1.9.B.3
- An argument is a value that is passed into a method when the method is called. The arguments passed to a method must be compatible in number and order with the types identified in the parameter list of the method signature. When calling methods, arguments are passed using call by value. Call by value initializes the parameters with copies of the arguments.
- 1.9.B.4
- Methods are said to be overloaded when there are multiple methods with the same name but different signatures.
- 1.9.B.5
- A method call interrupts the sequential execution of statements, causing the program to first execute the statements in the method before continuing. Once the last statement in the method has been executed or a return statement is executed, the flow of control is returned to the point immediately following where the method was called.
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];
Read what Saavi narrates
(upbeat, warm music starts and fades to background)
Hello everyone, it’s Saavi from Shrutam US. Let's talk about one of the most important ideas in programming: telling your program what to do.
Imagine you're ordering a smoothie. You don't just say "give me a smoothie." You have to be specific. "I'd like a strawberry banana smoothie, large." That extra information is key. Calling a method in Java is exactly the same. You can't just tell the computer to `calculate`. You have to tell it *what* to calculate and give it the numbers it needs.
This is all about understanding a method's "signature"—its name and the data it needs—so you can call it correctly and know what to expect in return.
Let's look at an example. Imagine we have a video game, and we need to check if a player's score is a new high score. We might have a method defined in the documentation that looks like this: `isHighScore`, and it takes an integer `score` as a parameter. It returns a boolean, which is a true or false value.
So, a player named Marcus just scored 12,500 points. How do we use this method?
First, we look at the signature. The name is `isHighScore`. It needs one piece of information: an integer score. And, most importantly, it returns a boolean. That means it will give us back a `true` or `false` answer.
So, in our code, we'd call the method and pass in Marcus's score, which is 12,500. But since it gives a value back, we have to catch it! We can store this `true` or `false` answer in a variable... let's call it `newRecord`.
So the line looks like: imagine a variable called `newRecord` is set to the result of calling `isHighScore` with the value `12500`.
Now, the `newRecord` variable holds either `true` or `false`. We can use that in an `if` statement. If `newRecord` is true, we can print a message like, "Congratulations, Marcus! New high score!"
See how that works? We used the method's return value to control what our program did next.
A very common mistake here is to ignore that return value. If you just call a method that returns a value but don't store it or use it, that value just... disappears. It's like the computer did the calculation for you, whispered the answer, and you weren't listening. So always remember to catch the return value!
You're building the skills to command programs and make them do complex things. Keep practicing, stay curious, and you'll get it. You're more than capable.
(music fades up and out)
Calling `calculateSalesTax(10.00);` on its own line does nothing useful. The method calculates the tax, returns the value, but you didn't catch it or use it. The value vanishes instantly.
Always assign the result to a variable or use it in an expression, like `double tax = calculateSalesTax(10.00);` or `System.out.println(10.00 + calculateSalesTax(10.00));`.
`void` means "returns nothing." Code like `int result = myVoidMethod();` will not compile. There is no value to assign.
Call `void` methods on a line by themselves. Their job is to perform an action (like printing), not to provide data. `myVoidMethod();` is the correct syntax.
If a method signature is `doSomething(String, int)`, calling `doSomething(25, "Liam");` will fail. Java is strict about matching the type and order of arguments to the parameters.
Double-check the method signature in the documentation or code. Ensure your arguments match the parameter list exactly: `doSomething("Liam", 25);`.
While related, they are different. It leads to confusion when reading and writing code.
Remember: **P**arameters are **P**laceholders in the method definition. **A**rguments are the **A**ctual values you pass when you call the method.
If you pass an `int` variable `x` to a method, the method gets a *copy* of `x`'s value. If the method changes its parameter, the original `x` in your `main` code is unaffected.
Understand that for primitive types (`int`, `double`, `boolean`, etc.), methods work on copies. To "get" a changed value back, the method must `return` it.
`public void myMethod(int x)` and `public void myMethod(int y)` are NOT overloaded. They have the exact same signature: `myMethod(int)`. The parameter name doesn't matter. This will cause a compiler error for being a duplicate method.
To overload a method, you must change the number or type of parameters. For example, `myMethod(int x)` and `myMethod(double x)` are correctly overloaded.