PrepGo

Methods: How to Write Them - AP Computer Science A Study Guide

Written by AP Content Team, Verified for 2026 AP Exams, Last updated: May 2026

Learn with study guides reviewed by top AP teachers. This guide takes about 11 minutes to read.

Getting Started

In programming, we often need to perform the same task multiple times. Instead of writing the same block of code over and over, we can package it into a reusable unit. Methods are these fundamental, reusable units of code that perform a specific action, making our programs more organized, readable, and efficient.

What You Should Be Able to Do

  • Write a method with a specific name, parameters, and return type.

  • Implement methods that perform an action without returning a value (void).

  • Implement methods that perform a calculation and return a value.

  • Distinguish between a method's parameters (the definition) and the arguments passed during a method call.

  • Call a method and, if applicable, store its return value in a variable.

Key Concepts & Java Implementation

The Core Idea

A method is a named block of statements that can be executed by "calling" its name. The core principle behind methods is procedural abstraction. This means we can use a method (call it) without needing to know the complex details of how it works. We only need to know what it does, what inputs it needs (parameters), and what output it provides (return value).

For example, to find the square root of a number, we can call Math.sqrt(25.0). We don't need to know the complex mathematical algorithm used to calculate the square root; we just trust that it will return the correct answer. This abstraction allows us to break down large, complex problems into smaller, more manageable sub-problems, each solved by a specific method.

Methods can be categorized into two main types:

  1. void Methods: These methods perform an action, such as printing to the console or modifying an object's state. They do not send back any value to the caller.

  2. Return Methods: These methods compute a value and send it back to the part of the code that called it. The return keyword is used to specify the value being sent back.

Syntax & Implementation

A method is defined within a class. Its definition, often called the method declaration, consists of a method signature and a method body.

  • Syntax Table: The Method Signature
ComponentPurposeJava Example (public int add(int num1, int num2))
Access ModifierDetermines visibility (e.g., public, private). We will primarily use public.public
Return TypeThe data type of the value the method returns. Use void if it returns nothing.int
Method NameThe name used to call the method. By convention, it starts with a lowercase letter (camelCase).add
Parameter ListA comma-separated list of input variables (type name) inside parentheses. Can be empty.(int num1, int num2)
  • Annotated Java Examples

1. A void Method with a Parameter

A void method performs an action but does not return a value. This example takes a String as input and prints a personalized greeting.


public class Greeter {

    // This method takes one String parameter and prints a message.

    // The return type is 'void' because it doesn't return any data.

    public void sayHello(String name) {

        // The method body contains the code to be executed.

        System.out.println("Hello, " + name + "!");

    }

}

2. A Method that Returns a Value

This method takes two integers as input, calculates their sum, and uses the return keyword to send the result back to the caller.


public class Calculator {

    // This method takes two int parameters and returns their sum.

    // The return type is 'int' because it returns an integer value.

    public int add(int a, int b) {

        int sum = a + b;

        // The 'return' statement sends the value of 'sum' back.

        // The type of the returned value MUST match the return type.

        return sum;

    }

}

Tracing & Analysis

  • Execution Trace

Let's trace the execution of calling the add method and storing its result.

Code:


Calculator myCalc = new Calculator();

int result = myCalc.add(5, 8); // Method call

System.out.println(result);

Trace:

  1. A Calculator object myCalc is created.

  2. The add method on myCalc is called. The argument5 is passed to the parametera. The argument 8 is passed to the parameter b.

  3. Inside the add method:

    • A local variable sum is created.

    • sum is assigned the value of a + b, which is 5 + 8, or 13.

  4. The statement return sum; is executed. The method immediately stops, and the value 13 is sent back to where the method was called.

  5. The returned value 13 is assigned to the variable result.

  6. System.out.println(result); prints 13 to the console.

  • Analysis

The return keyword is crucial. It does two things: it specifies the value to be sent back and it immediately terminates the method's execution. Any code inside a method after a return statement is unreachable and will cause a compile-time error. A method with a void return type cannot return a value, but it can use return; (with no value) to exit the method early.

Java Syntax Quick-Reference

  • return value;: Exits the current method and sends value back to the caller. The type of value must match the method's declared return type.

  • void: A keyword used as a return type to indicate that the method does not return any value.

  • methodName(type param1, type param2): The syntax for defining a method's name and its list of parameters. Each parameter must have a data type and a name.

Core Code Examples & Terminology

  • Method: A named block of code that performs a specific task and can be called from other parts of the program.

  • Method Signature: The part of a method declaration that includes the method name and its parameter list (the number, type, and order of parameters).

  • Parameter: A variable declared in a method's signature that acts as a placeholder for an input value.

  • Argument: The actual value or expression passed to a method when it is called.

  • Return Type: The data type of the value a method sends back to its caller. This is specified before the method name in the signature.

  • Procedural Abstraction: The practice of separating the "what a method does" (its interface) from "how it does it" (its implementation), allowing programmers to use methods without knowing their internal details.

  • Core Snippet 1 (Void Method):

    
    public void displayScore(int score) {
    
        System.out.println("Final Score: " + score);
    
    }
    

    This method performs an action (printing to the console) and does not return a value.

  • Core Snippet 2 (Return Method):

    
    public double calculateAverage(int total, int count) {
    
        return (double) total / count;
    
    }
    

    This method performs a calculation and returns a double result to the caller.

Core Skill Check

  • Code Tracing: What is the final value of y after this Java code runs: public int compute(int x) { return x * 2 + 1; } int y = compute(5);?

    • Answer: 11
  • Debugging: Identify the compile-time error in this Java code: public int getStatus() { System.out.println("Status is OK."); }.

    • Answer: Missing return statement. The method is declared to return an int but does not return anything.
  • Application: Write a single line of Java code that calls a method double getArea(double r) with an argument of 10.0 and stores the result in a variable named circleArea.

    • Answer: double circleArea = getArea(10.0);

Common Misconceptions & Errors

  • Forgetting a return Statement: If a method is declared with a return type other than void (e.g., int, String), it must have a return statement that returns a value of that type along every possible code path.

  • Mismatching Return Type: The value you return must be of the same data type as the method's declared return type (or be convertible to it). You cannot return a String from a method declared to return an int.

  • Ignoring a Return Value: Calling a method that returns a value but not doing anything with the result (e.g., calculateAverage(100, 10);). This is not a syntax error, but the computed value is lost, which is usually a logical error.

  • Assigning a void Call to a Variable: You cannot assign the result of a void method call to a variable, as it returns nothing. The code String message = sayHello("World"); will cause a compile-time error.

Summary

Methods are the fundamental organizational units in Java, allowing for code reuse and problem decomposition through procedural abstraction. Every method has a signature that defines its name, parameters, and return type. Methods declared as void perform an action and do not return a value. Methods with a specific return type (like int or double) must use the return keyword to send a value of that type back to the caller. Understanding how to write and call methods is essential for building any non-trivial Java application.