Back

Activity 3.1 Defining and Invoking Methods

divider

Introduction

Introduction to Methods in Java

Breaking Programs into Smaller, Reusable Parts

What Are Methods?

Methods (aka functions or procedures) are blocks of code that perform a specific task.

They allow us to reuse logic, organize our programs, and simplify complex tasks.

Built-in Methods

You've already been using methods in every Java program so far.

System.out.println("Hello world!");

You may not know how System.out.println() works behind the scenes, but that's okay. Methods are designed so you can use functionality without needing to understand every detail.

This is known as abstraction.

Key Benefits of Using Methods

  • Reusability: Write code once and use it multiple times.
  • Modularity: Break down complex problems into smaller, manageable parts.
  • Readability: Make code easier to understand and maintain.
  • Debugging: Find and fix errors in isolated sections.

Components of a Method

public static void greeting()
{
System.out.println("Hey buddy!");
System.out.println("How are you?");
}

Header: Declares the method's access level, return type, name, and parameters.

Components of a Method

public static void greeting()
{
System.out.println("Hey buddy!");
System.out.println("How are you?");
}

Header: Declares the method's access level, return type, name, and parameters.

Body: Contains the instructions that run when the method is called.

Components of a Method Header

public static void greeting()
{
System.out.println("Hey buddy!");
System.out.println("How are you?");
}

In this example:

  • public static - modifiers that control visibility and behavior.

Components of a Method Header

public static void greeting()
{
System.out.println("Hey buddy!");
System.out.println("How are you?");
}

In this example:

  • public static - modifiers that control visibility and behavior.
  • void - the return type (no value is returned).

Components of a Method Header

public static void greeting()
{
System.out.println("Hey buddy!");
System.out.println("How are you?");
}

In this example:

  • public static - modifiers that control visibility and behavior.
  • void - the return type (no value is returned).
  • greeting - the method name.

Components of a Method Header

public static void greeting()
{
System.out.println("Hey buddy!");
System.out.println("How are you?");
}

In this example:

  • public static - modifiers that control visibility and behavior.
  • void - the return type (no value is returned).
  • greeting - the method name.
  • () - parentheses (empty for now).

Defining a Method ≠ Calling a Method

Defining a method describes what it does, but it doesn't run until you call or invoke it.

public class Example {
public static void main(String[] args) {
greeting(); // Method call
greeting(); // Call it again
}
public static void greeting() {
System.out.println("Hey buddy!");
System.out.println("How are you?");
}
}

Each time greeting() is called, the same code runs again — a simple example of code reuse.

Variable Scope

Variables declared inside a method exist only within that method.

public static int randomNumber() {
int randomNumber = (int)(Math.random() * 10);
}
public static void revealAnswer() {
❌System.out.println("The secret number was " + randomNumber);
}

Local Variables: Declared inside a method — only accessible there.

Once a method finishes running, its local variables are deleted from memory.

Methods in Practice

  • Keep main() short and easy to read.
  • Group related behavior into its own section of code.

Next Lesson Preview

Parameters and Return Values

So far, our methods don't take any input or return any output.

In the next lesson, you'll learn how to make your methods more flexible by:

  • Passing arguments into a method.
  • Returning values back to the caller.

Key Terms

Method
A named block of code that performs a specific task. Methods make programs modular, reusable, and easier to read.
Method Header
The first line of a method declaration that specifies its access level, return type, name, and parameter list.
Method Body
The code block inside curly braces that contains the instructions the method will execute.

Key Terms

Return Type
Specifies the type of value a method sends back to the caller. If a method doesn't return a value, its return type is void.
Method Call (Invocation)
The statement that executes a method by using its name followed by parentheses. i.e. "Using the method".
Local Variable
A variable declared inside a method. It can only be accessed within that method and is removed from memory once the method finishes.

Key Terms

Scope
The region of a program where a variable can be accessed. Local variables have method-level scope.
Abstraction
The concept of using methods or classes without knowing the full details of how they work internally.
Modularity
Dividing a program into independent sections or modules, such as methods, to simplify design and debugging.

Key Terms

Code Reuse
The practice of writing a method once and using it multiple times instead of duplicating code.

'F' → Fullscreen

Objectives

  • icon Define and invoke simple void methods in Java.
  • icon Explain how methods improve readability and organization.
  • icon Use methods to structure a simple console-based program.
divider

Activity Tasks

  • icon Create a new Java file named 3-1-Methods.
  • icon Complete each task individually and run your program to verify the output.

Task 1: Create and Call Methods

  • icon Define three methods: showIntro(), displayMenu(), and gameOver().
  • icon Each method should print a short message related to its name.
  • icon From main(), call these methods in sequence.
Program.java
import java.util.Scanner;
public class Program
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String choice;
showIntro();
displayMenu();
// To Do: Menu System
}
static void showIntro()
{
System.out.println("=== MINI GAME COLLECTION VOL. 1 ===");
System.out.println("Welcome!");
System.out.println();
}
static void displayMenu()
{
System.out.println("1. Guess the Number");
System.out.println("2. Lucky Dice");
System.out.println("3. Spin the Wheel");
System.out.println("4. Exit");
System.out.println();
}
static void gameOver()
{
System.out.println("Thanks for playing!");
System.out.println("Goodbye!");
}
}

Task 2: Menu System

  • icon Implement the main menu system, and create the corresponding method definitions. The mini-game methods will be implemented in the next task.
Program.java
import java.util.Scanner;
public class Program
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String choice;
showIntro();
// move displayMenu() into the loop
do
{
displayMenu();
System.out.print("Choose mini-game: ");
choice = input.nextLine();
switch (choice)
{
case "1" -> playGuessTheNumber();
case "2" -> playLuckyDice();
case "3" -> playSpinTheWheel();
case "4" -> gameOver();
default -> System.out.println("Invalid choice.");
}
System.out.println();
} while (!choice.equals("4"));
}
static void showIntro()
{
3 collapsed lines
System.out.println("=== MINI GAME COLLECTION VOL. 1 ===");
System.out.println("Welcome!");
System.out.println();
}
static void displayMenu()
{
5 collapsed lines
System.out.println("1. Guess the Number");
System.out.println("2. Lucky Dice");
System.out.println("3. Spin the Wheel");
System.out.println("4. Exit");
System.out.println();
}
static void gameOver()
{
2 collapsed lines
System.out.println("Thanks for playing!");
System.out.println("Goodbye!");
}
static void playGuessTheNumber()
{
// To Do: Guess the Number Mini-Game
}
static void playLuckyDice()
{
// To Do: Lucky Dice Mini-Game
}
static void playSpinTheWheel()
{
// To Do: Spin the Wheel Mini-Game
}
}

Task 3: Implement Mini-Games

  • icon The Number Guessing mini-game has been implemented for you.
  • icon Implement the remaining mini-game methods. They don't need to be complex, but have some fun!
Program.java
import java.util.Scanner;
public class Program
{
public static void main(String[] args)
{
24 collapsed lines
Scanner input = new Scanner(System.in);
String choice;
showIntro();
do
{
displayMenu();
System.out.print("Choose mini-game: ");
choice = input.nextLine();
switch (choice)
{
case "1" -> playGuessTheNumber();
case "2" -> playLuckyDice();
case "3" -> playSpinTheWheel();
case "4" -> gameOver();
default -> System.out.println("Invalid choice.");
}
System.out.println();
} while (!choice.equals("4"));
}
static void showIntro()
{
3 collapsed lines
System.out.println("=== MINI GAME COLLECTION VOL. 1 ===");
System.out.println("Welcome!");
System.out.println();
}
static void displayMenu()
{
5 collapsed lines
System.out.println("1. Guess the Number");
System.out.println("2. Lucky Dice");
System.out.println("3. Spin the Wheel");
System.out.println("4. Exit");
System.out.println();
}
static void gameOver()
{
2 collapsed lines
System.out.println("Thanks for playing!");
System.out.println("Goodbye!");
}
static void playGuessTheNumber()
{
Scanner input = new Scanner(System.in);
System.out.println("--- Guess the Number ---");
System.out.print("Guess my secret number betwen 1 and 10: ");
int secret = (int)((Math.random() * 10) + 1);
int guess = input.nextInt();
System.out.println("It was " + secret + "!");
System.out.println(guess == secret ? "You Win!" : "You Lose!");
}
static void playLuckyDice()
{
Scanner input = new Scanner(System.in);
int die1 = (int)((Math.random() * 6) + 1);
int die2 = (int)((Math.random() * 6) + 1);
int bet;
System.out.println("--- Lucky Dice ---");
System.out.println();
}
static void playSpinTheWheel()
{
Scanner input = new Scanner(System.in);
int wheel = (int)((Math.random() * 25) + 1);
int bet;
System.out.println("--- Spin the Wheel ---");
System.out.println();
}
}
divider

Sample Output

Your program output should look similar to the sample output below.

Sample Output
=== MINI GAME COLLECTION VOL. 1 ===
Welcome!
1. Guess the Number
2. Lucky Dice
3. Spin the Wheel
4. Exit
Choose mini-game: 1
--- Guess the Number ---
Guess my secret number betwen 1 and 10: 7
It was 7!
You Win!
1. Guess the Number
2. Lucky Dice
3. Spin the Wheel
4. Exit
Choose mini-game: 4
Thanks for playing!
Goodbye!
divider

Reflection Questions

You may write your reflection answers as comments at the bottom of your code.

  1. What is the purpose of defining a method instead of placing all code in main()?
  2. How does invoking a method help you organize or reuse code?
  3. What patterns do you notice in how methods are defined and called?
divider

Submission

Submit your completed .java file and reflection answers to the appropriate dropbox.

Activity Complete