01 / 20

Defining Methods
in Java

Learn to create reusable blocks of code by defining methods with parameters and return types to write cleaner, more organized programs.

AP Computer Science

What Is a Method?

A method is a named block of code that performs a specific task. Instead of writing the same logic over and over, you write it once inside a method, then call that method whenever you need it.

Reusable
Write once, call many times from anywhere in your class.
Organized
Break complex problems into small, manageable pieces.
Testable
Each method can be tested and debugged independently.

Anatomy of a Method

public static int add ( int a , int b ) Modifiers (public, static) Return Type Method Name Parameters { return a + b; } Method Body

Why Methods Matter

Imagine you need to calculate the area of a rectangle in ten different places in your program. Without methods, you'd copy-paste the same formula ten times. With a method, you write it once and call it ten times.

Without Methods
\(w \times h\)  // line 12
\(w \times h\)  // line 47
\(w \times h\)  // line 83
\(w \times h\)  // line 109
Duplicated logic With Methods int area(int w, int h)
  { return \(w \times h\); }
area(5, 3); // call it! Single source of truth

The Method Signature

A method's signature is the combination of its name and parameter list. Java uses the signature to distinguish between methods, even if they share the same name (this is called overloading).

// Signature: add(int, int)
public static int add(int a, int b) {
  return a + b;
}

// Signature: add(double, double)
public static double add(double a, double b) {
  return a + b;
}

Return Types: void vs Value

void
The method performs an action but does not send a value back. You cannot assign its result to a variable.
Value-returning
The method computes something and sends a result back using the return keyword. Must match the declared type.
// void: performs action, returns nothing
public static void greet(String name) {
  System.out.println("Hello, " + name);
}

// int: computes and returns a value
public static int square(int n) {
  return n * n;
}

Parameters vs Arguments

These two terms are often confused, but they refer to different things. Parameters are the placeholders in the method definition. Arguments are the actual values you pass when calling the method.

DEFINITION (Parameters) int add(int a, int b) CALL (Arguments) int result = add(5, 3);

How to Define a Method

1
Choose the return type. Does the method produce a result? Use int, double, String, etc. If not, use void.
2
Name the method. Use camelCase, starting with a lowercase verb: calculateArea, printScore, isValid.
3
Declare the parameters. List each input's type and name inside parentheses. Use an empty () for no inputs.
4
Write the body. Place your logic inside curly braces { }. If non-void, include a return statement.

Example 1: A Simple void Method

public static void printLine(int length) {
  for (int i = 0; i < length; i++) {
    System.out.print("-");
  }
  System.out.println();
}

// Calling it:
printLine(20); // prints: --------------------

Example 2: A Value-Returning Method

public static double circleArea(double radius) {
  return Math.PI * radius * radius;
}

// Calling it and using the result:
double a = circleArea(5.0);
System.out.println(a); // 78.539...

Example 3: Multiple Parameters

public static String buildGreeting(String title, String name, int age) {
  return "Hello, " + title + " " + name
      + ". You are " + age + " years old.";
}

// Call:
String msg = buildGreeting("Dr.", "Smith", 45);
// "Hello, Dr. Smith. You are 45 years old."

How a Method Call Works

main() int x = add(3, 7); // pauses here... // x is now 10 add(int a, int b) a = 3, b = 7 return 3 + 7; // 10 call with (3, 7) returns 10 Step-by-step: 1. main() encounters add(3, 7) and pauses 2. Control jumps to add(): a gets 3, b gets 7 3. add() returns 10; control returns to main(); x = 10

Parameter Scope

Parameters and variables declared inside a method only exist within that method's curly braces. This is called local scope. Once the method finishes, those variables are destroyed.

public static int doubleIt(int x) {
  int result = x * 2; // result exists HERE only
  return result;
}

// In main():
int y = doubleIt(5); // y = 10
// System.out.println(result); // ERROR! result doesn't exist here

Common Mistakes

Missing Return
Declaring a non-void return type but forgetting the return statement. The compiler will reject the code.
Wrong Type
Returning a String from a method declared as int. The return value must match the declared type exactly.
Argument Mismatch
Passing the wrong number of arguments or the wrong types when calling a method. Order matters.

Comparing Method Types

void Methods Value-Returning Methods
Return type void int, double, String, etc.
return statement Optional (or return;) Required with a value
Can store result? No Yes: int x = method();
Use case Print, modify state Compute and return data
Example printLine(20); double area = circleArea(5.0);

Question 1 of 5

Which of the following is a valid method header in Java?

Question 2 of 5

What does the keyword void indicate in a method declaration?

Question 3 of 5

What is the result of calling average(7, 4)?

Question 4 of 5

What does the method mystery do?

Question 5 of 5

What happens when this code is compiled?