APrep Open the app

AP Computer Science A · Unit 3: Class Creation

3.6 Writing Methods

Method anatomy

A method has a header (access modifier, return type, name, parameter list) and a body enclosed in braces. The method signature is the name plus parameter list. If the return type isn't void, every path through the method must end with a return statement that returns a value matching that type.

Parameters vs. return values

Parameters are variables listed in the method header that receive values (arguments) passed in when the method is called. Java uses pass-by-value: primitive parameters get copies of the value, and object reference parameters get a copy of the reference (so the same object can still be modified). A method with return type void performs an action but returns nothing.

Writing correct methods

Break problems into smaller steps and write pre/post conditions — what must be true before calling the method and what will be true after. Use `this` to refer to the calling object's instance variables when needed. One method can call another method of the same class, including itself (recursion, covered later).

Key terms

Method signature
The method's name plus its parameter list (types and order), used to identify/overload methods.
Parameter
A variable in a method's header that receives a value (argument) passed in when the method is called.
Pass-by-value
Java's parameter-passing style: primitives are copied; object references are copied too, but both copies point to the same object.
void return type
Indicates a method performs an action but returns no value.
Precondition / Postcondition
Precondition: what must be true before calling a method. Postcondition: what is guaranteed true after it executes.

Try an AP-style question

Code

public static void change(int x) { x = 99; }
...
int n = 5;
change(n);
System.out.print(n);

What is printed?

  1. An error
  2. 5
  3. 99
  4. 0
Show the answer

B. Primitives are passed by value.

Practice 8 AP-style questions with instant explanations, flashcards and spaced review.

Study 3.6 free in APrep