Lesson 27 of 140
Written lesson · 15 min

Parameters, Arguments, and Return Values

Pass data into methods with parameters, return results with a return type, and use early return to keep methods clear.

Preview

You are viewing a free preview lesson.

Lesson Overview

In the previous lesson, we learned how to declare and call basic methods, for example:

java
static void greet() {
    System.out.println("Welcome!");
}

However, this method always produces the same output. In a real program, methods usually work with different data:

java
greet("Sakib");
greet("Subu");
greet("Sumu");

The same behavior should be reusable with different input, and a method that calculates something should be able to hand the result back to its caller instead of only printing it. In this lesson, we will learn how methods receive input through parameters and send results back with return.

Learning Objectives

After completing this lesson, you will be able to:

  • Distinguish between parameters and arguments
  • Pass input to a method
  • Use multiple parameters
  • Write value-returning methods
  • Choose an appropriate return type
  • Store and reuse returned values
  • Understand the difference between void and value-returning methods
  • Use early return
  • Understand return paths in non-void methods
  • Design simple reusable method signatures

Why Do Methods Need Input?

Consider:

java
static void greet() {
    System.out.println("Hello, Sakib!");
}

If we want to greet Subu with Hello, Subu!, we could create another method:

java
static void greetSubu() {
    System.out.println("Hello, Subu!");
}

But the behavior is the same. Only the data changes: the name. Therefore, the name should be an input to the method.

Parameters and Arguments

A parameter is a typed variable declared in a method declaration to receive input. In this method, name is the parameter and String is its type:

java
static void greet(String name) {
    System.out.println("Hello, " + name + "!");
}

An argument is the actual value provided for a parameter when a method is called. In greet("Sakib");, "Sakib" is the argument. Simply:

text
Parameter → What input the method expects
Argument  → What actual input is provided during the call

Different Arguments, Same Method

One method can be reused with different data:

java
public class Main {

    public static void main(String[] args) {
        greet("Sakib");
        greet("Subu");
        greet("Sumu");
    }

    static void greet(String name) {
        System.out.println("Hello, " + name + "!");
    }
}

Output:

text
Hello, Sakib!
Hello, Subu!
Hello, Sumu!

Parameters Have Types

Java is statically typed. Therefore, every parameter has a type. This method expects an int, so printAge(30); is valid, while printAge("thirty"); does not compile, because "thirty" is a String:

java
static void printAge(int age) {
    System.out.println(age);
}

Variables and Expressions as Arguments

An argument does not have to be a literal. Here, the current value of learnerName is passed to the method:

java
String learnerName = "Sakib";
greet(learnerName);

An expression can be an argument too. In the call printTotal(10 + 20);, for a method static void printTotal(int total), the expression is evaluated first (10 + 20 → 30). Then 30 is passed to the method as the argument.

Multiple Parameters

A method can receive multiple inputs:

java
static void printCourse(String title, long priceInPaisa) {
    System.out.println(title + " - " + priceInPaisa);
}

Call:

java
printCourse("Java and OOP Foundation", 499_000L);

Parameter Order Is Important

For static void printProfile(String name, int age), the call printProfile("Sakib", 30); maps the values by position: "Sakib" goes to name and 30 to age. The call printProfile(30, "Sakib"); is wrong, because the types do not match the expected positions.

Be More Careful When Parameters Have the Same Type

java
static void printFullName(String firstName, String lastName) {
    System.out.println(firstName + " " + lastName);
}

Both of these calls compile:

java
printFullName("Samiul", "Sakib");
printFullName("Sakib", "Samiul");

Java cannot understand semantic intent from the types alone. Therefore, clear parameter names and logical ordering are important.

Parameters Are Local Variables

A parameter can be used like a local variable inside its method. However, the name parameter of greet(String name) is not available outside the method. Each method call receives its own parameter value: in greet("Sakib"); the parameter name is "Sakib", and in a following greet("Jalisa"); it is "Jalisa".

What Is a Return Value?

Some methods, like greet(String name), only perform an action. Others calculate a result and return it to the caller. This method returns an int:

java
static int add(int first, int second) {
    return first + second;
}

Return Type

The type before the method name tells us what type of value the method returns. In static int add(int first, int second), int is the return type.

return

The statement return first + second; does two things:

  1. Evaluates the expression
  2. Sends the result back to the caller

For example, after int result = add(10, 20);, the variable result holds 30.

Returning Different Types

A method can return any type, for example int, String, boolean or long:

java
static int getAge() {
    return 30;
}

static String createGreeting(String name) {
    return "Hello, " + name + "!";
}

static boolean isAdult(int age) {
    return age >= 18;
}

static long calculateTotal(long priceInPaisa, int quantity) {
    return priceInPaisa * quantity;
}

Return Type and Returned Value Must Be Compatible

getAge() above promises an int and returns 30. This version does not compile, because the returned value is a String; javac reports error: incompatible types: String cannot be converted to int:

java
static int getAge() {
    return "thirty";
}

Using a Returned Value

Besides being stored in a variable, as result was above, a returned value can be used directly:

java
System.out.println(add(5, 7));

Output:

text
12

The method call acts as its returned value within the expression. A returned value can also be used in a condition. Here, isAdult(20) evaluates and returns true:

java
if (isAdult(20)) {
    System.out.println("Adult");
}

A Returned Value Can Be an Argument to Another Method

java
static int doubleValue(int value) {
    return value * 2;
}

static void printNumber(int number) {
    System.out.println(number);
}

In the call printNumber(doubleValue(10));, Java first runs doubleValue(10), which returns 20, and then calls printNumber(20), which prints 20.

Method Calls Can Be Composed

java
static int add(int first, int second) {
    return first + second;
}

static int multiply(int first, int second) {
    return first * second;
}

In int result = multiply(add(2, 3), 4);, the inner call runs first: add(2, 3) returns 5, then multiply(5, 4) returns 20.

void vs. Returning Method

Compare these two methods:

java
static void printTotal(int first, int second) {
    System.out.println(first + second);
}

static int calculateTotal(int first, int second) {
    return first + second;
}

The first method prints the result, and that is all the caller gets. The second returns the result, so the caller decides what to do with it: print it, store it, or use it in a condition such as if (calculateTotal(2, 3) > 4). The calculation does not decide how the result is displayed, which is why a returning method is generally more flexible for calculations.

return Ends Method Execution

When return executes, the current method invocation ends immediately. A statement cannot be written after an unconditional return:

java
static int getNumber() {
    return 10;
    System.out.println("Hello");
}

The final statement is unreachable, so the code does not compile. javac reports:

text
error: unreachable statement

Early Return

return can also exit from the middle of a method. Here, if age < 0, the method ends at that point:

java
static void printAge(int age) {
    if (age < 0) {
        System.out.println("Invalid age");
        return;
    }
    System.out.println("Age: " + age);
}

Early Return with a Value

java
static String classifyAge(int age) {
    if (age < 0) {
        return "Invalid";
    }
    if (age < 18) {
        return "Minor";
    }
    return "Adult";
}

Examples:

text
classifyAge(-1) → Invalid
classifyAge(15) → Minor
classifyAge(30) → Adult

Every Path in a Non-void Method Must Return a Value

Invalid:

java
static String getResult(boolean passed) {
    if (passed) {
        return "Passed";
    }
}

If passed == false, no value is returned, so the code does not compile. javac reports:

text
error: missing return statement

Correct:

java
static String getResult(boolean passed) {
    if (passed) {
        return "Passed";
    }
    return "Failed";
}

Basic Pass-by-Value

When a Java method is called, the argument's value is provided to the parameter. Primitive example:

java
static void changeNumber(int number) {
    number = 100;
}

Caller:

java
int value = 10;
changeNumber(value);
System.out.println(value);

Output:

text
10

The method parameter number receives its own local value. Changing that value does not change the caller's value variable.

We will study how this rule works with objects and references in more detail when we learn about objects.

Useful Method Signature

Look at this method:

java
static long calculateTotal(long priceInPaisa, int quantity)

From this declaration alone we can tell what the method does (calculateTotal), what input it needs (priceInPaisa and quantity), and what it gives back (a long). The method signature communicates the intent of the code.

Parameters Should Represent Only Necessary Input

calculateTotal() asks for exactly the two values it needs, the price and the quantity, and nothing else. The required input is visible in every call, such as calculateTotal(499_000L, 2).

Meaningful Method and Parameter Names

Good:

java
static boolean canEnroll(
        boolean coursePublished, boolean alreadyEnrolled)

Weak:

java
static boolean check(boolean a, boolean b)

Names help make the code understandable.

Complete Example

java
public class Main {

    public static void main(String[] args) {
        long total = calculateTotal(499_000L, 2);
        boolean largeOrder = isLargeOrder(total);
        String message = createOrderMessage(total, largeOrder);

        System.out.println(message);
    }

    static long calculateTotal(long priceInPaisa, int quantity) {
        return priceInPaisa * quantity;
    }

    static boolean isLargeOrder(long total) {
        return total > 500_000L;
    }

    static String createOrderMessage(long total, boolean largeOrder) {
        if (largeOrder) {
            return "Large order: " + total;
        }
        return "Order total: " + total;
    }
}

Output:

text
Large order: 998000

Here, every method has clear input and output.

Important Terms

Parameter

A typed input variable declared in a method declaration.

Argument

The actual value or expression provided during a method call.

Return Type

The type of value a method produces.

Return Value

The actual result returned by the method to the caller.

return

Ends the current method invocation and, when needed, sends a result back to the caller.

Method Signature

The method's name and parameter structure, which help describe the method call contract.

Predict the Result

Question 1

What does this program print?

java
public class Main {

    public static void main(String[] args) {
        int score = 70;
        addBonus(score);
        System.out.println(score);

        score = addBonus(score);
        System.out.println(score);
    }

    static int addBonus(int score) {
        score = score + 10;
        return score;
    }
}

Answer

text
70
80

The parameter score is a separate local variable that receives a copy of the value 70, even though it has the same name. The first call changes only that copy, and its returned value is ignored. The second call stores the returned 80 back into the caller's variable.

Question 2

What does this program print?

java
public class Main {

    public static void main(String[] args) {
        System.out.println(grade(90));
        System.out.println(grade(40));
    }

    static String grade(int score) {
        if (score >= 50) {
            return "Pass";
        }
        if (score >= 80) {
            return "Excellent";
        }
        return "Fail";
    }
}

Answer

text
Pass
Fail

90 >= 50 is checked first, so grade(90) returns "Pass" and the method ends; the "Excellent" check is never reached. With early returns, the order of the checks matters: put the most specific one first.

Question 3

Does this program compile?

<!-- error -->
java
public class Main {

    public static void main(String[] args) {
        System.out.println(label(3));
    }

    static String label(int count) {
        if (count > 0) {
            return "Some";
        } else if (count <= 0) {
            return "None";
        }
    }
}

Answer

No. javac reports error: missing return statement. We can see that one of the two conditions is always true, but the compiler does not reason about the values of conditions: it only sees an if/else if with no final else, so a path without return seems possible. Replace else if (count <= 0) with else, or end the method with a return.

Question 4

Does this program compile?

<!-- error -->
java
public class Main {

    public static void main(String[] args) {
        System.out.println(printTotal(2, 3));
    }

    static void printTotal(int first, int second) {
        System.out.println(first + second);
    }
}

Answer

No. javac reports error: 'void' type not allowed here. printTotal() prints the sum but returns nothing, so there is no value for System.out.println() to print. Either call printTotal(2, 3); on its own, or change the method to return an int.

Common Mistakes

Returning the wrong type and a missing return on some path are shown with their compiler messages in the teaching sections above. These are the other mistakes beginners meet most.

Arguments That Do Not Match the Parameters

The arguments must match the parameters in number, order and type. For static void greet(String name) and static void printProfile(String name, int age), all of these are wrong:

java
greet();                    // missing argument
greet("Sakib", "Subu");     // one argument too many
printProfile(30, "Sakib");  // order swapped, so the types do not fit

javac rejects each one with error: method ... cannot be applied to given types, followed by the parameters it expected and the arguments it found. Read that message: it tells you exactly what the call should look like.

Returning a Value from a void Method

Wrong:

java
static void calculate() {
    return 10;
}

javac reports error: incompatible types: unexpected return value. A void method can use return; to stop early, but it cannot return a value. If the caller needs the result, change void to the result's type.

Ignoring a Returned Value

calculateTotal(100, 5); is legal, but the returned total is thrown away immediately, so the call achieves nothing. Store or use the result: long total = calculateTotal(100, 5);. Predict the Result Question 1 shows how easy this is to miss.

Practice Exercise 1: Greeting

Solutions: lesson 2.10.

Create static void greet(String name) and call it with three different names. It prints:

text
Hello, <name>!

Practice Exercise 2: Add Two Numbers

Create static int add(int first, int second) and return the sum of the two numbers.

Practice Exercise 3: Rectangle Area

Create static int calculateArea(int width, int height). For example, calculateArea(5, 4) returns 20.

Practice Exercise 4: Adult Check

Create static boolean isAdult(int age). Return true if age is 18 or above.

Practice Exercise 5: Largest Number

Create static int max(int first, int second). Do not use Math.max().

Practice Exercise 6: Score Classification

Create static String classifyScore(int score) with these rules:

text
Below 0 or above 100 → Invalid
90+                  → Excellent
70+                  → Good
Otherwise            → Needs Improvement

Practice Exercise 7: Predict the Output

Predict the output, then run the program to check:

java
public class Main {

    public static void main(String[] args) {
        int value = add(multiply(2, 3), subtract(10, add(1, 4)));
        System.out.println(value);
        System.out.println(multiply(value, 2));
    }

    static int add(int first, int second) {
        return first + second;
    }

    static int subtract(int first, int second) {
        return first - second;
    }

    static int multiply(int first, int second) {
        return first * second;
    }
}

Knowledge Check

Question 1

What is a parameter?

Question 2

What is an argument?

Question 3

What is the difference between a parameter and an argument?

Question 4

Why do parameters make a method reusable?

Question 5

Why does a parameter need a type?

Question 6

What does the return type tell us?

Question 7

What does return do?

Question 8

What is the difference between void and an int return type?

Question 9

Can a returned value be stored in a variable?

Question 10

Can a returned value be used as an argument to another method?

Question 11

What happens to a method when return executes?

Question 12

What is required from every possible path in a non-void method?

Question 13

If a primitive argument is changed through the method parameter, does the caller variable automatically change?

Question 14

Why are meaningful method and parameter names important?

Knowledge Check Answers

Answer 1

A typed variable declared in a method declaration that receives input from a method call.

Answer 2

The actual value or expression provided for a parameter when a method is called.

Answer 3

A parameter is part of the method declaration. An argument is the actual input supplied during the call.

Answer 4

The same method can work with different input values.

Answer 5

Java is statically typed, so the method needs to know what kind of input it accepts.

Answer 6

It tells us what type of value the method returns to the caller.

Answer 7

It ends the current method invocation and, for a value-returning method, sends the result back to the caller.

Answer 8

A void method does not return a result value. An int method returns an integer-compatible value.

Answer 9

Yes.

Answer 10

Yes.

Answer 11

The current method invocation ends immediately, and execution returns to the caller.

Answer 12

A compatible return value.

Answer 13

No.

Answer 14

They help the reader understand what the method does and what each input means by looking at the signature.

Lesson Summary

In this lesson, we learned:

  • Parameters are typed local variables that declare a method's inputs; arguments are the values a call provides, matched by number, order and type
  • The return type states what a method gives back, and return sends that value to the caller and ends the method
  • A returned value can be stored, used in a condition, or passed straight into another method call
  • Returning a calculation instead of printing it lets the caller decide what to do with the result
  • Early return ends a method as soon as the answer is known, and every path of a non-void method must return a value
  • Primitive arguments are passed by value: reassigning a parameter never changes the caller's variable
  • Clear method and parameter names make a signature describe the method's contract

Think first

Coming soon

Checkpoint questions that ask you to commit to an answer before the lesson shows it.