# Creating and Using Methods

> Chapter 9 of the Courseiva ORACLE-JAVA-FOUNDATIONS curriculum — https://courseiva.com/learn/oracle-java-foundations/methods-and-parameters

**Official objective:** 3.1 — Define and invoke methods, pass arguments, and return values.

## Introduction

Creating and using methods is the single most important skill for organising your Java code so that it does not become an unreadable mess. For the 1Z0-811 exam, you need to know how to define a method, how to call one, how to pass information into it, and how to get a result back out – because these skills underpin every real-world Java program.

## The Master Chef Recipe Analogy

A head chef in a busy restaurant kitchen does not rewash, chop, and boil every single vegetable every time a customer orders a soup. Instead, the chef writes a recipe card – a standard set of instructions – for 'prepare vegetable stock'. That recipe card lives in the kitchen's recipe book. When a ticket for minestrone comes in, the chef calls out 'Prepare vegetable stock!' to the sous chef. The sous chef follows the steps on that card exactly: take carrots, peel, chop, add water, simmer for 1 hour, strain. The result is a pot of stock that the chef then uses to build the minestrone. If the head chef later wants a different soup – say, a creamy pumpkin – she can call the same 'prepare vegetable stock' recipe again. She does not have to explain the chopping and simmering steps all over again; she just invokes the recipe by name. This saves time, keeps the kitchen consistent, and hides the messy details of peeling and chopping. In Java, a method is exactly that recipe card. It is a named block of code that you write once and can 'invoke' (call) by its name from anywhere in your program. You pass it ingredients (arguments), it performs its steps, and it can hand you back a finished dish (a return value). The recipe does not change just because you use it for different soups – it always does the same job, which is what makes methods so powerful.

## Core explanation

A method in Java is a named block of code that performs a specific task. Think of it as a mini-program inside your larger program. Methods exist for two main reasons: they help you avoid repeating yourself (the 'Don't Repeat Yourself' or DRY principle), and they help you break a complex problem into smaller, more manageable pieces.

**Why you need methods**
Imagine you are writing a program that calculates the total price for a shopping basket, including tax. Without methods, you would write the tax-calculation logic every single time you need it – in the checkout section, in the refund section, in the invoice printing section. If the tax rate changes, you have to hunt down every single copy and change it. That is error-prone and exhausting. With a method, you write the tax calculation once, call it whenever you need it, and change it in only one place when the rules update.

**How to define a method**
Every method in Java has a structure. The most important parts are:
- Access modifier (like `public` or `private`) – this controls who can use the method. For the 1Z0-811 exam, you mostly deal with `public`.
- Return type – what kind of data the method gives back. For example, `int` for whole numbers, `double` for decimals, `String` for text, or `void` if it gives nothing back.
- Method name – a descriptive camelCase name like `calculateTax` or `printReceipt`.
- Parameters – variables in parentheses that receive values from the caller. These act like containers that hold the data you send in.
- Method body – the block of code in curly braces `{}` that does the work.

Here is what a simple method definition looks like:
```java
public double calculateTax(double price, double taxRate) {
    double tax = price * taxRate;
    return tax;
}
```
This method is called `calculateTax`. It expects two pieces of data: a `price` and a `taxRate`, both `double` numbers. It multiplies them to get the `tax`, then uses the keyword `return` to send that `tax` value back to whoever called it.

**How to invoke (call) a method**
Using a method is simple: you write its name followed by parentheses, and inside those parentheses you put the values you want to send (the arguments). For the method above, you would call it like this:
```java
double result = calculateTax(100.0, 0.08);
```
Here, `100.0` is passed into the `price` parameter, and `0.08` is passed into `taxRate`. The method runs, computes `8.0`, and that value is returned and stored in the variable `result`.

**Passing arguments**
Arguments are the actual values you send into a method when you call it. They must match the parameters in order and type. If the method expects `(int, double)`, you cannot give it `(String, int)` – the compiler will stop you. This is called 'type safety'.

**Returning values**
The `return` keyword does two things: it immediately exits the method, and it sends a value back to the caller. If a method declares a return type other than `void`, it must always return a value of that type. A `void` method can use `return;` without a value just to exit early.

**The anatomy of a method signature**
The method signature is the method name plus the parameter list. For example, `calculateTax(double, double)` is the signature. Two methods can have the same name if they have different signatures – this is called method overloading, which you will also see in the exam.

**Common terms to know**
- Parameter: the variable defined in the method definition that receives the argument.
- Argument: the actual value you pass when calling the method.
- Return type: the data type of the value the method sends back.
- Method body: the code inside the curly braces.
- Calling/invoking a method: the act of using the method’s name with arguments to execute its code.

When you call a method, the program's execution 'jumps' to that method, runs its code line by line, and then 'jumps' back to where it was called, picking up where it left off. This flow is fundamental to understanding how programs are structured.

## Real-world context

A junior developer at an e-commerce company is assigned to build the checkout system for the website. The system needs to calculate the final price for an order, which includes applying a discount, adding tax, and adding shipping cost. Without methods, the junior developer writes hundreds of lines of spaghetti code inside a single `main` method. The code is hard to read, and when the business team changes the discount rule from '10% off orders over $50' to '15% off orders over $75', the developer must manually search through the entire block to find the discount logic. That is risky and time-consuming.

Instead, the senior developer shows them how to break the task into methods:
- A `calculateDiscount` method that takes the order total and returns the discount amount.
- A `calculateTax` method that takes the discounted total and the tax rate, and returns the tax amount.
- A `calculateShipping` method that decides the shipping cost based on weight and distance.
- A `calculateFinalPrice` method that calls all three and adds everything up.

Now, changing the discount rule is simple: the developer opens just the `calculateDiscount` method, updates the logic, and the change propagates everywhere that method is called. The business team tests only that method, not the entire checkout flow.

**Step-by-step in a real sprint**
- The developer writes a unit test for `calculateDiscount` with sample inputs (e.g., order total of $100 should give a $15 discount).
- They run the test – it fails because the method is not implemented yet.
- They write the method body: `double discount = total * 0.15; return discount;`.
- They run the test again – it passes.
- They repeat for `calculateTax`, `calculateShipping`, and `calculateFinalPrice`.
- Finally, they integrate these methods into the main checkout flow. Each method is independently testable, reusable, and easy to maintain.

This approach is standard practice in professional software development. Every major codebase – from banking apps to video games – relies on well-named methods to keep code organised. When you interview for IT roles, you will often be asked to 'refactor' a long block of code into methods, which shows that you understand how to write clean, maintainable code.

The exam tests these fundamentals because they are not just academic – they are the day-to-day reality of every Java developer.

## Exam focus

The 1Z0-811 exam tests Creating and Using Methods through several distinct question patterns. You must be prepared for each.

**Method definition syntax**
The exam loves to give you a method header with deliberate mistakes – missing return type, wrong access modifier, curly braces in the wrong place. You must recognise that a method always requires a return type (or `void`) and parentheses. A typical question: 'Which of the following defines a valid method?' with options like:
- `public void myMethod() {...}` – valid.
- `public myMethod() {...}` – invalid because the return type is missing.
- `void public myMethod() {...}` – invalid because the modifier order is wrong (modifier before return type).

**Calling methods**
You will see questions where you must trace the output of a program that calls methods. For example, the main method calls a method that changes a variable and returns something. The trick: primitive types (like `int`, `double`) are passed by value, meaning the method gets a copy of the value – changes inside the method do not affect the original variable. The exam often sets a trap where a method doubles a number inside itself but the original variable outside stays unchanged.

**Return types**
Multiple-choice questions will ask: 'What does this method return?' with a snippet. You must identify the return type from the method header and know that a `void` method cannot have a `return` statement with a value. Also, if a method declares a non-void return type, every code path must return a value. The exam likes to show a method with an `if-else` where only the `if` branch returns, and the `else` branch does not – that is a compile error.

**Parameters vs arguments**
A classic trap: the question uses the terms 'parameter' and 'argument' interchangeably. You must know that the method definition has parameters (placeholders), and the method call has arguments (actual values). The exam may define a method `void foo(int x)` and call it with `foo(5)`. They will ask: 'What is the parameter?' (answer: `x`). 'What is the argument?' (answer: `5`).

**Method overloading**
The exam expects you to understand that methods can have the same name if their parameter lists differ in type, number, or order. A common question: 'Which of these methods overloads `void print(int a)`?' The correct answer must have the same name `print` but a different parameter list (e.g., `void print(double a)` or `void print(int a, int b)`). A method with a different return type but same parameters is not overloading – it is a duplicate, which causes a compile error.

**Common traps**
- Forgetting that the method execution stops immediately when it hits `return`. Sometimes a question shows code after a `return` statement and asks if it compiles – it does not.
- Confusing `System.out.println()` with a method that returns something. `println` is `void` – it does not produce a value you can assign to a variable.
- Thinking that changing a primitive parameter inside a method affects the caller – it does not.

**What to memorise**
- The exact syntax: `modifier returnType methodName(parameterList) { body }`.
- The difference between `void` and a returning method.
- How method overloading works: same name, different parameter list.
- That arguments must match parameters in type and order.
- The `return` keyword exits the method and sends a value.

Practise by writing small methods on paper and tracing the flow. The exam is closed-book, so understanding the flow is essential.

## Step by step

1. **Identify the task the method will perform** — Before writing any code, decide what single, specific job the method should do. For example, 'calculate the tax on a given price'. This keeps the method focused and reusable.
2. **Choose the access modifier and return type** — For most exam examples, use `public`. Decide if the method returns data – if so, pick the correct type (e.g., `double` for decimals, `int` for whole numbers). If it just performs an action like printing, use `void`.
3. **Name the method and list the parameters** — Use a descriptive camelCase name (e.g., `getTotal`). Inside parentheses, declare each parameter with its type and name, separated by commas. For zero parameters, leave the parentheses empty.
4. **Write the method body inside curly braces** — The body contains the statements that accomplish the task. Use the parameters as variables. If the method returns something, use `return` with the value. Ensure every code path that reaches the end of a returning method has a `return` statement.
5. **Call the method by name with the correct arguments** — When invoking the method, write its name followed by parentheses containing the arguments in the same order and type as the parameters. If the method returns a value, you can assign it to a variable or use it directly in an expression.

## Comparisons

### Parameter vs Argument

**Parameter:**
- Defined in the method declaration inside parentheses.
- Acts as a placeholder variable that receives a value.
- Exists only within the method body.
- Example: In `void foo(int x)`, `x` is a parameter.

**Argument:**
- Passed in the method call inside parentheses.
- The actual value or variable being passed.
- Exists in the calling code.
- Example: In `foo(5);`, `5` is the argument.

### void Method vs Returning Method

**void Method:**
- Declares `void` as the return type.
- Does not give back any value after execution.
- May use `return;` to exit early, but no value is returned.
- Cannot be used on the right side of an assignment.

**Returning Method:**
- Declares a specific return type (e.g., `int`, `String`).
- Must use `return value;` to send back a value.
- The return value can be assigned to a variable or used in an expression.
- Every code path must return a value of the declared type.

### Method Signature vs Method Body

**Method Signature:**
- Consists of method name and parameter list.
- Used by the compiler to distinguish overloaded methods.
- Does not include the access modifier or return type.
- Example: `calculateTax(double, double)` is the signature.

**Method Body:**
- The code block inside curly braces {} following the signature.
- Contains the statements that execute when the method is called.
- Can include variable declarations, loops, and other method calls.
- The size and complexity vary based on the method's task.

## Diagram

_Flowchart showing the process of defining a method (with its signature) and invoking it, including how execution jumps to the method body and returns a value._

```mermaid
flowchart TD
    A[Define Method] --> B[Method Signature]
    B --> C[Access Modifier: public]
    B --> D[Return Type: int, double, void, etc.]
    B --> E[Method Name: calculateTax]
    B --> F[Parameters: (double price, double rate)]
    A --> G[Method Body: statements in curly braces]
    G --> H[Use parameters as variables]
    G --> I[Return statement (if non-void)]
    J[Invoke/Call Method] --> K[Pass arguments: calculateTax(100.0, 0.08)]
    K --> L[Execution jumps to method body]
    L --> M[Method runs and returns value]
    M --> N[Caller receives value]
```

## Common misconceptions

- **Misconception:** Changing a primitive parameter inside a method changes the original variable in the calling code. **Reality:** Java passes primitives by value, so the method works on a copy. The original variable outside the method remains unchanged. (This is confusing because many languages allow pass-by-reference, and learners assume Java does the same. The exam explicitly tests this misconception.)
- **Misconception:** A method must always have at least one parameter. **Reality:** A method can have zero parameters. For example, `public void greet() { ... }` defines a method with an empty parameter list. (Beginners see examples with parameters and think they are mandatory, but methods that need no external data (like printing a fixed message) are perfectly valid.)
- **Misconception:** If a method has a non-void return type, you must store the returned value in a variable when you call it. **Reality:** You can call a returning method and ignore its return value. For example, `getNumber();` is valid even if `getNumber()` returns an `int`. The value is simply discarded. (Many beginners assume the compiler forces you to use the return value, but Java allows you to ignore it. The exam may show a call without assignment and ask if it is legal – it is.)
- **Misconception:** A method can return multiple values at once using multiple `return` statements. **Reality:** A method can only return one value. The `return` statement immediately exits the method, so only the first `return` encountered is executed. (Learners see `return` used in if-else blocks and think multiple returns happen, but only one executes. They confuse the ability to have multiple `return` lines (with only one running) with returning multiple values.)

## Key takeaways

- A method is a named block of code that is defined once and can be invoked multiple times from different places in a program.
- Every method must have a return type – use `void` if the method does not give back a value.
- Arguments are the actual values passed into a method call; parameters are the placeholders defined in the method header.
- Java passes primitive types by value – changes to the parameter inside the method do not affect the original argument.
- Method overloading allows multiple methods with the same name but different parameter lists (type, number, or order).
- The `return` keyword immediately exits the current method and optionally sends a value back to the caller.

## FAQ

**Can I define a method inside another method in Java?**

No, you cannot. In Java, methods must be defined directly inside a class, not inside another method. If you try to nest a method, the code will not compile.

**What happens if I forget to use `return` in a method that declares a non-void return type?**

The code will not compile. Java's compiler checks that every code path inside a non-void method ends with a `return` statement that provides a value of the declared type.

**Can I call a method from inside the same method?**

Yes, that is called recursion – a method calling itself. It is allowed as long as there is a condition to stop the recursion, otherwise you will get a `StackOverflowError`.

**Is the order of arguments important when calling a method?**

Yes, the arguments must match the parameters in the exact order they are declared in the method definition. Passing them in the wrong order will cause a type mismatch or logical errors.

**Can a method return a String?**

Yes. You can declare a method with return type `String` and use `return "some text";`. Strings are objects in Java, but they are perfectly valid return types.

**What is the difference between `System.out.println()` and a method that returns a value?**

`println` is a `void` method – it prints something to the screen but does not give any value back. A returning method, like `int getNumber()`, gives a value back that you can assign to a variable or use in calculations.

## Check your understanding

1. **What is the return type of a method that does not return any value?**

   Answer: The return type is `void`. A `void` method cannot use `return` with a value.

2. **What is the output of this code snippet?
```java
public class Main {
    public static void main(String[] args) {
        int x = 5;
        change(x);
        System.out.println(x);
    }
    public static void change(int num) {
        num = 10;
    }
}
```**

   Answer: The output is 5. Java passes primitives by value, so `change` modifies a copy of `x`; the original remains unchanged.

3. **Can the following two methods exist in the same class? `public void foo(int a)` and `public int foo(int a)`**

   Answer: No. Overloading requires different parameter lists. These two methods have the same name and same parameter list but different return types, which is not allowed and causes a compile error.

4. **What does the `return` keyword do inside a method?**

   Answer: It immediately exits the current method, and if a value is provided, it sends that value back to the caller.

5. **What is the difference between a method parameter and a method argument?**

   Answer: A parameter is a variable defined in the method's declaration that receives data. An argument is the actual value passed into the method when it is called.

---

Interactive version with quiz and diagrams: https://courseiva.com/learn/oracle-java-foundations/methods-and-parameters
