MOBI BOOT CAMP CORP. logoLearning Buddy
  • SIGN IN
  • Introduction
  • Unit 0: The First Program
  • Unit 1: Using Objects and Methods
  • Unit 2: Selection and Iteration
  • Unit 3: Class Creation
    • Part 1: Basic Concepts
    • Part 2: Methods
      • Methods: How to Write Them
      • Methods: Passing and Returning References of an Object
      • Class Variables and Methods
      • Scope and Access
      • this Keyword
      • Unit 3 Part 2 Slides
  • Unit 4: Data Collections

Unit 3.5: Methods: How to Write Them

Methods define the behaviors of an object—the actions it can perform.

Functional Encapsulation
  • Methods allow us to bundle logic into named, reusable blocks. This not only promotes code reuse but also makes the code more readable and easier to debug by isolating specific tasks.

Methods allow us to organize code into reusable blocks.

Void Methods

A void method performs an action but does not give any data back to the code that called it.

  • The method header must include the word void.

Task: Implementing a basic void method.

public void sayHello() {
    System.out.println("Hello!"); // Just performs an action
}

Non-Void Methods

A non-void method is like a vending machine: you call it, and it "spits out" a single piece of data (a value).

  • Instead of void, the header specifies the return type (like int, double, or String).

Task: Implementing a non-void method that returns a value.

public int getLuckyNumber() {
    return 7; // Gives back an integer
}

Return by Value

When a non-void method finishes, it evaluates the expression next to the return keyword and sends that value back. This is called return by value.

Task: Returning the result of a calculation.

public double calculateTax(double price) {
    return price * 0.08; // Evaluates this math and returns the result
}

The return Keyword

The return keyword immediately stops the method and sends control back to whoever called it.

  • Unreachable Code: You cannot put any code after a return statement in the same block. It will cause a compiler error.
  • Early Exit: A return can be used inside an if statement or a loop to stop the method early. If it's inside a loop, it stops the loop and exits the method immediately.

Task: Using return for early method termination.

public void checkAge(int age) {
    if (age < 0) {
        return; // Stops the method immediately if age is invalid
    }
    System.out.println("Age is valid.");
}

Accessor Methods (Getters)

An accessor method allows other classes to "see" or get a copy of an object's private data.

  • Accessors are always non-void methods.

Task: Implementing an accessor (getter) method.

public class Player {
    private int score;
    
    // Accessor (Getter)
    public int getScore() {
        return score; 
    }
}

Mutator Methods (Setters)

A mutator method (also called a modifier) is used to change the value of an object's data.

  • Mutators are often void methods.

Task: Implementing a mutator (setter) method.

public class Player {
    private int score;

    // Mutator (Setter)
    public void setScore(int newScore) {
        score = newScore;
    }
}

Method Parameters

Parameters are the inputs a method needs to do its job. They are defined in the parentheses of the method header.

Task: Defining a method with multiple parameters.

// 'name' and 'times' are parameters
public void repeatName(String name, int times) {
    for (int i = 0; i < times; i++) {
        System.out.println(name);
    }
}

Pass by Value (Primitives)

When you pass a primitive (like int, double, or boolean) to a method, Java sends a copy of that value.

  • If the method changes its local copy of the parameter, it does not change the original variable outside the method.

Task: Demonstrating that primitives are passed by value.

public void increment(int x) {
    x = x + 1; // Only changes the local copy
}

// --- In main ---
int myNum = 10;
increment(myNum);
System.out.println(myNum); // Still prints 10!

Examples

Complete Class: TemperatureSensor

This example combines all the concepts of method design.

Task: Reviewing a complete class with accessors, mutators, and behaviors.

public class TemperatureSensor {
    private double currentTemp;

    public TemperatureSensor(double startTemp) {
        currentTemp = startTemp;
    }

    // Accessor
    public double getTemp() {
        return currentTemp;
    }

    // Mutator with validation
    public void setTemp(double newTemp) {
        if (newTemp > -273.15) { // Cannot be below absolute zero
            currentTemp = newTemp;
        }
    }

    // Void method with parameter
    public void logStatus(String location) {
        System.out.println("Sensor at " + location + " reads: " + currentTemp);
    }
}
Privacy Policy | Terms & Conditions