Fiveable
Fiveable
AP Computer Science A

💻ap computer science a review

2.4 Calling a Void Method With Parameters

Verified for the 2025 AP Computer Science A examLast Updated on June 18, 2024

Parameters add flexibility and power to methods, allowing the same method to perform actions with different inputs. In Java, void methods with parameters let us customize an object's behavior based on the data we provide. Understanding how to call these methods with appropriate parameters is essential for effective Java programming.

Method Signatures with Parameters

A method signature for a method with parameters consists of the method name and the ordered list of parameter types. This signature uniquely identifies the method among others with the same name.

  • System.out.printIn : a Java statement used to display output on the console. It prints the specified message or value and adds a new line character at the end.
// Method signature: setAge(int)
public void setAge(int age) {
    this.age = age;
}

// Method signature: printDetails(String, int)
public void printDetails(String name, int id) {
    System.out.println("Name: " + name + ", ID: " + id);
}

The signature doesn't include the parameter names, only their types. For example, the signature of printDetails(String name, int id) is simply printDetails(String, int).

Parameter Order and Type Matching

Values provided in the parameter list need to correspond to the order and type in the method signature. When you call a method, the arguments (actual values) must match the parameters (formal parameters) in:

  1. Number: The same number of arguments as parameters
  2. Order: Arguments in the same order as parameters
  3. Type: Each argument compatible with its corresponding parameter type
public class Student {
    public void enrollInCourse(String courseName, int courseId, double fee) {
        // Method implementation
    }
    
    public static void main(String[] args) {
        Student student = new Student();
        
        // Correct call - parameters match in number, order, and type
        student.enrollInCourse("Computer Science", 101, 599.99);
        
        // Incorrect calls:
        // student.enrollInCourse("Physics", 299.99, 102);  // Type mismatch
        // student.enrollInCourse("Math");                 // Missing parameters
        // student.enrollInCourse(102, "English", 399.99); // Wrong order
    }
}

Method Overloading

Methods are said to be overloaded when there are multiple methods with the same name but a different signature. Overloading allows for methods that perform similar functions but with different parameter combinations.

public class Calculator {
    // Overloaded methods - same name, different signatures
    
    // add(int, int)
    public void add(int a, int b) {
        System.out.println("Sum of two integers: " + (a + b));
    }
    
    // add(int, int, int)
    public void add(int a, int b, int c) {
        System.out.println("Sum of three integers: " + (a + b + c));
    }
    
    // add(double, double)
    public void add(double a, double b) {
        System.out.println("Sum of two doubles: " + (a + b));
    }
    
    // add(String, String)
    public void add(String a, String b) {
        System.out.println("Concatenated strings: " + a + b);
    }
}

When you call an overloaded method, Java determines which version to execute based on the argument types you provide:

Calculator calc = new Calculator();
calc.add(5, 10);            // Calls add(int, int)
calc.add(5, 10, 15);        // Calls add(int, int, int)
calc.add(5.5, 10.5);        // Calls add(double, double)
calc.add("Hello, ", "World"); // Calls add(String, String)

Common Void Methods with Parameters

String Manipulation Methods

String text = "Hello";
text = text.concat(" World");      // Parameter: another String
System.out.println(text.substring(0, 5));  // Parameters: start and end indices

ArrayList Methods

ArrayList<String> names = new ArrayList<>();
names.add("Alice");                // Parameter: element to add
names.add(0, "Bob");               // Parameters: index and element to add
names.set(1, "Charlie");           // Parameters: index and new value
names.remove("Bob");               // Parameter: element to remove

Custom Class Methods with Parameters

public class BankAccount {
    private String accountNumber;
    private double balance;
    
    public BankAccount(String accountNumber) {
        this.accountNumber = accountNumber;
        this.balance = 0.0;
    }
    
    // Void method with parameter
    public void deposit(double amount) {
        if (amount > 0) {
            balance += amount;
            System.out.println("Deposited: $" + amount);
        } else {
            System.out.println("Invalid deposit amount");
        }
    }
    
    // Another void method with parameter
    public void withdraw(double amount) {
        if (amount > 0 && amount <= balance) {
            balance -= amount;
            System.out.println("Withdrawn: $" + amount);
        } else {
            System.out.println("Invalid withdrawal or insufficient funds");
        }
    }
    
    // Void method with multiple parameters
    public void transfer(double amount, BankAccount recipient) {
        if (amount > 0 && amount <= balance && recipient != null) {
            balance -= amount;
            recipient.deposit(amount);
            System.out.println("Transferred: $" + amount);
        } else {
            System.out.println("Transfer failed");
        }
    }
}

Parameter Type Compatibility

Java allows for some automatic type conversions when passing arguments to methods:

public class TypeExample {
    // Method that takes a double parameter
    public void showValue(double value) {
        System.out.println("Value: " + value);
    }
    
    public static void main(String[] args) {
        TypeExample example = new TypeExample();
        
        int intValue = 42;
        example.showValue(intValue);  // int automatically converted to double
        
        // But not all conversions are automatic:
        double doubleValue = 3.14;
        // example.showValue((int)doubleValue);  // Requires explicit cast
    }
}

Best Practices for Method Parameters

  1. Use Meaningful Parameter Names: Make parameter names descriptive to improve code readability

    // Good
    public void setDimensions(double length, double width, double height) { ... }
    
    // Not as clear
    public void setDimensions(double l, double w, double h) { ... }
    
  2. Validate Parameters: Check that parameter values are valid before using them

    public void setAge(int age) {
        if (age >= 0) {
            this.age = age;
        } else {
            System.out.println("Age cannot be negative");
        }
    }
    
  3. Limit the Number of Parameters: Methods with too many parameters can be hard to use correctly

    // Consider breaking this into multiple methods or using objects
    public void createUser(String name, String email, String phone, String address,
                          String city, String state, String zip) { ... }
    

Remember that parameters make methods more flexible and reusable. By understanding how to properly call void methods with parameters, you can effectively interact with objects and utilize their behaviors in different contexts.

Key Terms to Review (13)

CalculateSum: CalculateSum is an operation that involves adding up multiple numbers together to obtain their total sum.
CalculateArea: CalculateArea refers to the process of determining the size or extent of an enclosed shape or region using mathematical formulas or algorithms. It is commonly used in programming when working with geometric shapes.
CalculateAverage: CalculateAverage refers to the process of finding the mean value of a set of numbers by adding them up and dividing by the total count.
CalculateDiscount: CalculateDiscount means determining how much money can be saved from an original price by applying a percentage reduction.
Constructor Signature: A constructor signature refers to the unique combination of a class's name and its parameter types. It helps create instances (objects) of that class with specific initial values.
Method Signature: A method signature refers to the unique combination of a method's name and its parameter types. It helps distinguish one method from another.
Overloading Methods: Overloading methods refers to defining multiple methods with the same name but different parameters in a class. This allows for flexibility and reusability by providing different ways to perform similar tasks.
Outputs: Outputs refer to the results or values that are produced by a program or function when it is executed.
PrintAverage: PrintAverage refers to displaying or outputting the calculated average value on a screen or paper.
PrintSum: PrintSum refers to an action where the computed sum of multiple numbers is displayed on some physical medium for viewing purposes.
PrintArea: The term printArea refers to a function or method that outputs the calculated area of a shape onto a physical medium, such as paper or a computer screen.
System.out.println: System.out.println is a Java statement used to display output on the console. It prints the specified message or value and adds a new line character at the end.
Void Methods: Void methods are methods in programming that do not return a value. They perform a specific task or action, but they do not produce any output.