Fiveable
Fiveable
AP Computer Science A
Find gaps with guided practice
Guided practice grid visualization
Table of Contents

💻ap computer science a review

5.6 Writing Methods

Verified for the 2025 AP Computer Science A examCitation:

Methods with parameters are powerful tools that allow objects to receive information from the outside world and use it to perform actions or calculations. In a public class, these methods enable objects to interact with other parts of your program. Understanding how parameters work is essential for writing flexible, reusable code. This section explores how methods handle parameters, the distinction between formal and actual parameters, and the important concept of aliasing when working with object references. By mastering these concepts, you'll be able to design methods that effectively communicate with other parts of your program, whether you're working with primitive types like int and boolean or reference types like String and Student objects.

Method Parameters: The Basics

A method parameter is a variable that:

  • Is declared in the method header within a public method
  • Receives a value when the method is called
  • Can be used within the method body
  • Exists only for the duration of the method call

Java methods can accept parameters of any type—primitive types like int and boolean, or reference types like String and Student. This flexibility allows methods to work with a wide variety of data.

There are two important parameter-related terms to understand:

  1. Formal Parameter: The variable declared in the method header
  2. Actual Parameter: The value or expression passed when the method is called
public class Example {
    // The parameter 'message' is a formal parameter
    public void displayMessage(String message) {
        System.out.println(message);
    }
    
    public void testMethod() {
        // "Hello, world!" is the actual parameter
        displayMessage("Hello, world!");
        
        // A variable can also be an actual parameter
        String greeting = "Welcome!";
        displayMessage(greeting);
    }
}

Parameter Scope and Access

Methods can only access the private data and methods of a parameter that is a reference to an object when:

  • The parameter is the same type as the method's enclosing class
  • The parameter and method are in the same class
public class Student {
    private String name;
    private int id;
    
    // This method can access privateField because otherStudent
    // is the same type as the enclosing class
    public boolean hasSameId(Student otherStudent) {
        // Can access otherStudent's private id field
        return this.id == otherStudent.id;
    }
    
    // This method cannot access Car's private fields
    public void drive(Car car) {
        // WRONG: Cannot access car's private fields
        // car.fuelLevel = 100;
        
        // CORRECT: Must use public methods to interact
        car.refuel(20);
    }
}

How Methods Use Parameters

Non-void methods with parameters:

  • Receive values through parameters
  • Use those values in calculations or operations
  • Return a computed value of the specified type
public class Calculator {
    public int add(int a, int b) {
        return a + b;
    }
    
    public double calculateArea(double radius) {
        return Math.PI * radius * radius;
    }
    
    public String repeat(String text, int times) {
        String result = "";
        for (int i = 0; i < times; i++) {
            result += text;
        }
        return result;
    }
}

Passing Primitive vs. Reference Types

Java handles primitive and reference types differently when passing them to methods:

Primitive Parameters

When an actual parameter is a primitive value (like int, double, or boolean):

  • The formal parameter is initialized with a copy of that value
  • Changes to the formal parameter have no effect on the corresponding actual parameter
public class PrimitiveExample {
    public void modifyValue(int value) {
        value = value * 2;  // Modifies the local copy only
        System.out.println("Inside method: " + value);
    }
    
    public void test() {
        int x = 10;
        System.out.println("Before method call: " + x);
        modifyValue(x);
        System.out.println("After method call: " + x);  // Still 10, unchanged
    }
}

Reference Parameters

When an actual parameter is a reference to an object:

  • The formal parameter is initialized with a copy of the reference, not a copy of the object
  • Both references point to the same object (aliasing)
  • The method can use the reference to modify the object's state
public class ReferenceExample {
    public void modifyList(ArrayList<String> list) {
        list.add("New Item");  // Modifies the original list
    }
    
    public void test() {
        ArrayList<String> myList = new ArrayList<>();
        myList.add("Original Item");
        
        System.out.println("Before method call: " + myList);
        modifyList(myList);
        System.out.println("After method call: " + myList);  // Shows the modified list
    }
}

Aliasing with Reference Parameters

When passing a reference parameter, the formal parameter and the actual parameter become aliases—they both refer to the same object. This has important implications:

public class AliasingExample {
    public void modifyStudent(Student student) {
        // Both student and the original reference
        // point to the same Student object
        student.setName("Modified Name");
    }
    
    public void test() {
        Student s1 = new Student("Original Name", 12345);
        System.out.println("Before: " + s1.getName());
        
        modifyStudent(s1);
        System.out.println("After: " + s1.getName());  // Shows "Modified Name"
    }
}

Aliasing Diagram

Here's a visual representation of what happens with reference parameters:

Before method call:
                    +----------------+
s1 --------------> | Student object |
                    | name: "Original Name" |
                    +----------------+

During method call:
                    +----------------+
s1 --------------> | Student object |
                    | name: "Original Name" |
student ----------> +----------------+

After modification:
                    +----------------+
s1 --------------> | Student object |
                    | name: "Modified Name" |
student ----------> +----------------+

Best Practices: Modifying Parameters

It is generally good programming practice:

  • NOT to modify mutable objects that are passed as parameters (unless that's the method's explicit purpose)
  • To document any modifications a method will make to its parameters
  • To create and return a new object rather than modifying a parameter, when appropriate
// Approach 1: Modifying the parameter (use with caution)
public void addItem(ArrayList<String> list, String item) {
    list.add(item);
}

// Approach 2: Creating and returning a new object (often better)
public ArrayList<String> addItemToNewList(ArrayList<String> list, String item) {
    ArrayList<String> newList = new ArrayList<>(list);  // Make a copy
    newList.add(item);
    return newList;
}

Avoiding Common Mistakes with Parameters

Here are some common pitfalls to avoid:

  1. Assuming primitive parameters can be modified:

    // This will NOT work
    public void increment(int x) {
        x++;  // Only modifies the local copy
    }
    
  2. Reassigning reference parameters:

    // This will NOT modify the original reference
    public void resetList(ArrayList<String> list) {
        list = new ArrayList<>();  // Creates a new list, original reference unchanged
    }
    
  3. Forgetting that arrays are reference types:

    // This WILL modify the original array
    public void fillWithZeros(int[] arr) {
        for (int i = 0; i < arr.length; i++) {
            arr[i] = 0;
        }
    }
    

Complete Example: Handling Different Parameter Types

Here's a complete example demonstrating various parameter concepts:

public class ParameterExample {
    // Method with primitive parameters
    public double calculateAverage(int a, int b, int c) {
        return (a + b + c) / 3.0;
    }
    
    // Method with array parameter (reference type)
    public double calculateArrayAverage(int[] numbers) {
        int sum = 0;
        for (int num : numbers) {
            sum += num;
        }
        return numbers.length > 0 ? (double) sum / numbers.length : 0;
    }
    
    // Method with object parameter (reference type)
    public void updateStudent(Student student, int newGrade) {
        if (student != null && newGrade >= 0 && newGrade <= 100) {
            student.addGrade(newGrade);
        }
    }
    
    // Method that creates a new object instead of modifying the parameter
    public Student createUpdatedStudent(Student original, String newName) {
        if (original == null) {
            return null;
        }
        // Create a new student with the same ID but different name
        return new Student(newName, original.getId());
    }
    
    // Method demonstrating safe handling of mutable objects
    public ArrayList<Integer> getTopScores(ArrayList<Integer> scores, int topCount) {
        // Create a copy to avoid modifying the original
        ArrayList<Integer> scoresCopy = new ArrayList<>(scores);
        ArrayList<Integer> result = new ArrayList<>();
        
        // Sort the copy (not the original)
        Collections.sort(scoresCopy, Collections.reverseOrder());
        
        // Get the top scores
        int count = Math.min(topCount, scoresCopy.size());
        for (int i = 0; i < count; i++) {
            result.add(scoresCopy.get(i));
        }
        
        return result;
    }
}

Key Points to Remember

  • Methods can only access the private data and methods of a parameter if it's the same type as the method's enclosing class
  • Non-void methods with parameters receive values, use them, and return a computed result
  • When passing a primitive value, the formal parameter gets a copy of the value; changes to the parameter don't affect the original
  • When passing an object reference, the formal parameter becomes an alias to the same object; changes to the object are visible through both references
  • It's generally good practice not to modify mutable objects passed as parameters unless that's the explicit purpose of the method
  • Always consider whether to modify a parameter or create and return a new object

Key Terms to Review (22)

Access modifier: An access modifier is used in programming languages to control the visibility and accessibility of variables, methods, and classes within different parts of code. It determines whether other parts of code can access and modify certain elements.
Assignment: An assignment is the act of giving a value to a variable in programming. It involves storing information into memory locations so it can be accessed and manipulated later.
Boolean: A boolean is a data type that can only have two possible values: true or false. It is often used in programming to make decisions and control the flow of a program.
GetGradeDecimal(): The term "getGradeDecimal()" is a method or function used in programming to retrieve the numerical value of a student's grade. It returns the grade as a decimal number.
Int: The int is a primitive data type in Java used to store whole numbers without decimal points. It has a fixed size and represents integer values within a specific range.
Instance Variables: Instance variables are variables declared within a class but outside any method. They hold unique values for each instance (object) of the class and define the state or characteristics of an object.
Javadoc comments: Javadoc comments are special comments in Java that begin with /** and end with */. They are used to generate documentation for classes, methods, and fields, making it easier for other developers (including yourself) to understand how to use them.
@Override: The @Override annotation is used in Java to indicate that a method in a subclass is intended to override a method with the same name in its superclass. It helps ensure that the method signature and return type are correct.
Pass-by-value: Pass-by-value is the method of passing arguments to functions or methods by creating copies of their values instead of directly passing references to them.
Private: In the context of programming, private refers to a visibility modifier that restricts access to certain variables or methods within a class. It means that only other members of the same class can access those private elements.
Protected: In programming, "protected" is an access modifier that grants accessibility to members within subclasses or classes within the same package.
Public class: A public class is one that can be accessed and used by any other class or program. It serves as the blueprint for creating objects and contains variables and methods.
Public: Public is an access modifier in Java that indicates unrestricted visibility for classes, methods, and variables. Public members can be accessed from any other class or package.
Return Type: The return type in programming refers to the data type of the value that a method or function will return when it is called. It specifies what kind of data will be returned by the method.
ReturnCurrentAssignment(): This term refers to a method in programming that retrieves the current assignment. It is used to access and display the details of the assignment that is currently being worked on.
SetName(): setName() is a function or method used in programming to assign or change the name associated with an object or variable. It allows you to update or set a new name for an entity within your program.
SetGradeLevel(): In programming, setGradeLevel() is a method used to assign or update the grade level of an individual. It allows you to specify which grade level someone belongs to within your program.
Static: In programming, "static" refers to a variable or method that belongs to the class itself, rather than an instance of the class. It can be accessed without creating an object of the class.
Student: A student is an individual who is enrolled in a school or educational institution and is actively pursuing knowledge and education.
String: A String is a sequence of characters in Java, enclosed in double quotes. It represents text and can be manipulated using various methods.
SubmitAssignment(): The term "submitAssignment()" refers to a method or function in programming that allows a user to send their completed work or task for evaluation or processing.
ToString(): The toString() method is used to convert an object into a string representation. It returns a string that represents the state of the object.