Function parameters & arguments in Java


So far, the functions we've created execute a fixed task without context / inputs. But most often we want our functions to produce different outcomes depending on the context behind the function call.

For example, it would be nice if sayHello() would print a personalized message such as "Hello humans" or "Hello cats" or "Hello dogs", depending on the audience instead of "Hello world" no matter what.


Function parameters:

Function parameters allow functions to accept input(s) and perform a task using the input(s). We use parameters as placeholders for information that will be passed to the function when it is called.

When a function is defined, its parameters are specified between the parentheses that follow the function name.

Here is our function with one String parameter, audience:

void sayHello(String audience) {
  System.out.println("Hello " + audience);
}

Calling with arguments:

Then we can call sayHello() and specify the values in the parentheses that follow the function name. The values that are passed to the function when it is called are called arguments.

// Function declaration:
void sayHello(String audience) {
	System.out.println("Hello " + audience);
}

// Function call:
sayHello("humans"); // Output: Hello humans

We have passed one string argument: "humans". Inside the function audience will equal string "humans" and acts just like a regular variable.


Multiple parameters:

A function can have as many parameters as it needs. Here is a function with two parameters:

void sayHello(String name, int age) {
  System.out.println(name + ", aged " + age);
}

// Let's call it:
sayHello("John", 30); // Output: John, aged 30
sayHello("Mary", 26); // Output: Mary, aged 26

Notice that the order in which arguments are passed and assigned follows the order that the parameters are declared.


Variables as arguments:

Variables can also be passed as arguments for function calls:

void sayHello(String name, int age) {
  System.out.println(name + ", aged " + age);
}

String name = "Andy";
int age = 28;

sayHello(name, age); // Output: Andy, aged 28

sayHello("Mary", age); // Output: Mary, aged 28

Assignment
Follow the Coding Tutorial and let's write some functions.


Hint
Look at the examples above if you get stuck.


Introduction

In this lesson, we will explore the concept of function parameters and arguments in Java. Understanding how to use parameters and arguments is crucial for writing flexible and reusable code. This concept is widely used in various programming scenarios, such as handling user inputs, processing data, and creating dynamic outputs.

Understanding the Basics

Function parameters are placeholders for the values that will be passed to the function when it is called. These values, known as arguments, are provided during the function call. By using parameters and arguments, we can make our functions more dynamic and adaptable to different situations.

For example, consider a function that prints a greeting message. By using a parameter, we can customize the greeting based on the input provided:

void sayHello(String audience) {
  System.out.println("Hello " + audience);
}

In this example, audience is a parameter that will hold the value passed during the function call.

Main Concepts

Let's delve deeper into the key concepts of function parameters and arguments:

Here is an example with multiple parameters:

void sayHello(String name, int age) {
  System.out.println(name + ", aged " + age);
}

// Function calls:
sayHello("John", 30); // Output: John, aged 30
sayHello("Mary", 26); // Output: Mary, aged 26

In this example, the function sayHello has two parameters: name and age. The arguments provided during the function call are assigned to these parameters in the order they are passed.

Examples and Use Cases

Let's look at some examples to understand how function parameters and arguments can be used in different contexts:

void greetUser(String name) {
  System.out.println("Welcome, " + name + "!");
}

void displaySum(int a, int b) {
  System.out.println("Sum: " + (a + b));
}

// Function calls:
greetUser("Alice"); // Output: Welcome, Alice!
displaySum(5, 10); // Output: Sum: 15

In the first example, the greetUser function takes a single parameter name and prints a welcome message. In the second example, the displaySum function takes two parameters a and b and prints their sum.

Common Pitfalls and Best Practices

When working with function parameters and arguments, it's important to keep the following points in mind:

Advanced Techniques

As you become more comfortable with function parameters and arguments, you can explore advanced techniques such as:

void printNumbers(int... numbers) {
  for (int number : numbers) {
    System.out.println(number);
  }
}

// Function call:
printNumbers(1, 2, 3, 4, 5); // Output: 1 2 3 4 5

In this example, the printNumbers function uses varargs to accept a variable number of integer arguments.

Code Implementation

Here is a complete example demonstrating the use of function parameters and arguments in Java:

public class Main {
  // Function with one parameter
  static void sayHello(String audience) {
    System.out.println("Hello " + audience);
  }

  // Function with multiple parameters
  static void sayHello(String name, int age) {
    System.out.println(name + ", aged " + age);
  }

  public static void main(String[] args) {
    // Calling functions with arguments
    sayHello("humans"); // Output: Hello humans
    sayHello("John", 30); // Output: John, aged 30
    sayHello("Mary", 26); // Output: Mary, aged 26

    // Using variables as arguments
    String name = "Andy";
    int age = 28;
    sayHello(name, age); // Output: Andy, aged 28
  }
}

Debugging and Testing

When debugging and testing functions with parameters and arguments, consider the following tips:

import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;

public class MainTest {
  @Test
  void testSayHello() {
    assertEquals("Hello humans", captureOutput(() -> Main.sayHello("humans")));
    assertEquals("John, aged 30", captureOutput(() -> Main.sayHello("John", 30)));
  }

  // Helper method to capture output
  private String captureOutput(Runnable runnable) {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    System.setOut(new PrintStream(out));
    runnable.run();
    return out.toString().trim();
  }
}

Thinking and Problem-Solving Tips

When approaching problems related to function parameters and arguments, consider the following strategies:

Conclusion

In this lesson, we explored the concept of function parameters and arguments in Java. We learned how to define functions with parameters, call functions with arguments, and handle multiple parameters. Understanding these concepts is essential for writing flexible and reusable code. Keep practicing and experimenting with different scenarios to master the use of function parameters and arguments.

Additional Resources

For further reading and practice, consider the following resources: