Java Methods

What are Methods?

A method is a named set of statements that can be called from elsewhere in the program code by its name. Methods are like reusable pieces of code that perform specific tasks. You've already been using methods like System.out.println() and Integer.valueOf() - these are pre-made Java methods.

Why Use Methods?

Methods help structure programs by breaking them into smaller, manageable pieces. Instead of writing long, complex code in one place, you can create methods that handle specific tasks. This makes your code easier to read, debug, and reuse.

Method Structure:

// Basic method structure
public static void methodName() {
    // Method body - code to execute
    System.out.println("This method does something!");
}

// Method with parameters
public static void greet(String name) {
    System.out.println("Hello, " + name + "!");
}

// Method that returns a value
public static int addNumbers(int a, int b) {
    return a + b;
}

// Method placement in a class
public class RobotProgram {
    public static void main(String[] args) {
        // Call methods from main
        greet("Robot");
        int result = addNumbers(5, 3);
        System.out.println("Sum: " + result);
    }
    
    // Methods go here, outside of main but inside the class
    public static void greet(String name) {
        System.out.println("Hello, " + name + "!");
    }
    
    public static int addNumbers(int a, int b) {
        return a + b;
    }
}

Method Parameters

Parameters are values given to a method that can be used in its execution. The parameters are defined within the parentheses following the method name. When you call the method, you pass values (arguments) that get copied into these parameters.

Single Parameter Example:

// Method with one parameter
public static void setMotorPower(double power) {
    System.out.println("Setting motor power to: " + power);
    // Code to actually set motor power would go here
}

// Calling the method
public static void main(String[] args) {
    setMotorPower(0.5);    // Pass 0.5 as the power value
    setMotorPower(1.0);    // Pass 1.0 as the power value
    
    // You can also pass expressions
    double targetPower = 0.75;
    setMotorPower(targetPower);        // Pass variable value
    setMotorPower(0.25 + 0.25);       // Expression evaluates to 0.5
}

Multiple Parameters Example:

// Method with multiple parameters
public static void driveRobot(double forward, double strafe, double rotate) {
    System.out.println("Drive command - Forward: " + forward + 
                      ", Strafe: " + strafe + ", Rotate: " + rotate);
    // Robot driving code would go here
}

// Method that calculates and returns a value
public static double calculateDistance(double x1, double y1, double x2, double y2) {
    double deltaX = x2 - x1;
    double deltaY = y2 - y1;
    return Math.sqrt(deltaX * deltaX + deltaY * deltaY);
}

// Calling methods with multiple parameters
public static void main(String[] args) {
    // Parameters are passed in the same order as defined
    driveRobot(0.8, 0.0, 0.2);  // forward=0.8, strafe=0.0, rotate=0.2
    
    // Calculate distance between two points
    double dist = calculateDistance(0, 0, 3, 4);
    System.out.println("Distance: " + dist);  // Output: 5.0
}

Method Call Stack

When a method is called, the program creates a new 'frame' in memory to store the method's variables. This creates a call stack - methods are stacked on top of each other. When a method finishes, its frame is removed and execution returns to the calling method.

Call Stack Example:

public static void main(String[] args) {
    System.out.println("Starting main method");
    startRobot();  // Call startRobot method
    System.out.println("Back in main method");
}

public static void startRobot() {
    System.out.println("Robot starting...");
    initializeSensors();  // Call initializeSensors method
    System.out.println("Robot ready!");
}

public static void initializeSensors() {
    System.out.println("Initializing sensors...");
    System.out.println("Sensors ready!");
}

/* Output:
Starting main method
Robot starting...
Initializing sensors...
Sensors ready!
Robot ready!
Back in main method

Call stack visualization:
1. main() starts
2. main() calls startRobot() - stack: [main, startRobot]
3. startRobot() calls initializeSensors() - stack: [main, startRobot, initializeSensors]
4. initializeSensors() finishes - stack: [main, startRobot]
5. startRobot() finishes - stack: [main]
6. main() finishes - program ends
*/

Basic Method Examples:

public class Calculator {
    
    // Method that returns a value
    public int add(int a, int b) {
        return a + b;
    }
    
    // Method that doesn't return a value (void)
    public void printResult(int result) {
        System.out.println("Result: " + result);
    }
    
    // Method with no parameters
    public void sayHello() {
        System.out.println("Hello!");
    }
}

Method Naming Conventions

Method names should begin with a lowercase letter, and subsequent words should start with uppercase letters (camelCase). Method names should be descriptive verbs that clearly indicate what the method does. The code inside methods should be indented by four spaces.

Good vs Bad Method Names:

// [ERROR] BAD: Poor naming conventions
public static void This_method_says_woof ( ) {
System.out.println("woof");
}

public static void doStuff() {
    // What does this do?
}

public static void x() {
    // Too short, unclear
}

// [OK] GOOD: Proper naming conventions
public static void thisMethodSaysWoof() {
    System.out.println("woof");
}

public static void initializeRobotSensors() {
    System.out.println("Initializing all robot sensors...");
    // Clear purpose, proper camelCase
}

public static void calculateMotorPower() {
    // Descriptive name, proper indentation
    double power = 0.5;
    System.out.println("Motor power: " + power);
}

Method Components:

Method Structure:

  • public static: Keywords that define method visibility and type
  • Return type: void (no return), int, double, String, boolean, etc.
  • Method name: descriptive verb in camelCase
  • Parameters: input values in parentheses (type name)
  • Method body: code inside curly braces, indented 4 spaces

Methods Calling Other Methods

Methods can call other methods, creating a chain of execution. This is very useful for breaking complex tasks into smaller, manageable pieces. Each method call adds a new frame to the call stack.

Methods Calling Other Methods:

public class RobotController {
    public static void main(String[] args) {
        System.out.println("Starting robot program...");
        runAutonomousMode();
        System.out.println("Program complete!");
    }
    
    public static void runAutonomousMode() {
        System.out.println("Autonomous mode starting...");
        initializeRobot();
        executeMovementSequence();
        System.out.println("Autonomous mode complete!");
    }
    
    public static void initializeRobot() {
        System.out.println("Initializing robot systems...");
        initializeSensors();
        initializeMotors();
        System.out.println("Robot ready!");
    }
    
    public static void initializeSensors() {
        System.out.println("- Sensors initialized");
    }
    
    public static void initializeMotors() {
        System.out.println("- Motors initialized");
    }
    
    public static void executeMovementSequence() {
        moveForward(24);  // Move 24 inches forward
        turnRight(90);    // Turn 90 degrees right
        moveForward(12);  // Move 12 inches forward
    }
    
    public static void moveForward(double inches) {
        System.out.println("Moving forward " + inches + " inches");
    }
    
    public static void turnRight(double degrees) {
        System.out.println("Turning right " + degrees + " degrees");
    }
}

/* Output:
Starting robot program...
Autonomous mode starting...
Initializing robot systems...
- Sensors initialized
- Motors initialized
Robot ready!
Moving forward 24.0 inches
Turning right 90.0 degrees
Moving forward 12.0 inches
Autonomous mode complete!
Program complete!
*/

The Main Method

The main method is special - it's where your program starts executing. When you run a Java program, the operating system calls the main method first. All other methods are called from main or from methods that main calls.

Try It Yourself:

Exercise 1: Method Fundamentals

  • Create a simple greet method and call it multiple times
  • Build a method with parameters that prints robot status
  • Write a method that returns a calculated value
  • Create a complex method that calls other methods
Practice creating and calling methods:

Open full interactive app