Thuta Learning
Java
IntermediateProgrammingBeginner

Methods

JavaLesson 1325 min

What you'll walk away with

  • Write a static method with a return type, a name, a parameter list and a body
  • Tell parameters (names inside the method) from arguments (values passed at the call)
  • Explain that a non-void method must return on every path, and what void means
  • Predict how pass-by-value behaves for primitive and array/object arguments

Explain it simply

Explain it simply

A method is like a named recipe. Once the fried-rice recipe is written down, you just say "fried rice" whenever you want it instead of rewriting every step. You hand the recipe its ingredients (the parameters), and some recipes hand you back a finished dish (the return value).

Other recipes return nothing and just do a job, like setting the table or writing a shopping list. In Java those methods are declared void. Instead of piling everything into main, splitting each job into a small named method makes the program far easier to read, fix and test.

Problem → Why → Solution

The problem: copy-pasted calculations

The main method below totals three orders and applies a discount. The same formula is pasted three times, so changing the discount from 10% to 15% means editing three places. Notice the third order was missed: the compiler reports nothing, and one customer is simply charged the wrong price.

Main.java
public class Main {
  public static void main(String[] args) {
    int order1 = 20 * 3;
    order1 = order1 - order1 * 15 / 100;
    int order2 = 45 * 2;
    order2 = order2 - order2 * 15 / 100;
    int order3 = 12 * 10;
    order3 = order3 - order3 * 10 / 100; // forgot to update this copy
    System.out.println(order1 + " " + order2 + " " + order3);
  }
}

Why does this bug happen?

One rule, the discount formula, is scattered across three places. Move it into a single method such as static int discounted(int price, int quantity) and the rule lives in exactly one spot, so a change reaches every caller at once. The method's name also says what is happening far better than 20 * 3 - ... does.

Core concept: the parts of a method, and pass-by-value

Read the header static int calculateTotal(int price, int quantity) from left to right. static means it can be called on the class without creating an object; main itself is static, so for now our own methods are static too, and object methods arrive in the next lessons. int is the return type, calculateTotal is the name, and the brackets hold the parameter list. Every parameter needs its own type: int price, quantity is not allowed.

A parameter is the name used inside the method; an argument is the actual value passed at the call. In calculateTotal(20, 3), 20 lands in price and 3 in quantity, matched by position, not by name. The compiler checks how many arguments there are and their types, but it cannot notice two ints passed in the wrong order.

If the return type is not void, every path must return a value of that type, or you get the compile error "missing return statement". return also ends the method immediately. In a void method, a bare return; is only used to leave early.

Java passes every argument by value. For a primitive such as int, the value is copied, so changing the parameter inside the method never changes the caller's variable. For arrays and objects, what gets copied is not the object but the reference that points to it. So when the method changes something inside the object, as values[0] = ... does, the caller sees it, but assigning a brand-new object to the parameter changes nothing for the caller. Java has no pass-by-reference at all. Parameters and variables declared inside a method are local: they exist only while that call runs and vanish when it returns.

Mental model: every call hands over copies
  1. Evaluate the arguments left to right
  2. Copy each value or reference
  3. The body works on those copies
  4. return hands one value back

Changes made through a copied reference are visible to the caller; reassigning the parameter is not.

General pattern

java
static ReturnType methodName(Type param1, Type param2) {
  // work with param1 and param2
  return value; // must match ReturnType
}

static void doSomething(Type param) {
  // side effect only, nothing to return
}

ReturnType result = methodName(arg1, arg2);

Write the return type, the method name, then typed parameters in brackets. When you call a value-returning method, store the result in a variable or use it directly inside another expression. A void method is simply called as a statement.

Example: returning methods, void methods and pass-by-value

This example has four methods. greetUser() and calculateTotal() show the two kinds of method, while tryToReset() and doubleFirst() show both faces of pass-by-value. Before running it, predict what count and prices will print.

Main.java
import java.util.Arrays;

public class Main {
  static void greetUser(String name) {
    System.out.println("Hello, " + name + "!");
  }

  static int calculateTotal(int price, int quantity) {
    return price * quantity;
  }

  static void tryToReset(int count) {
    count = 0;
  }

  static void doubleFirst(int[] values) {
    values[0] = values[0] * 2;
  }

  public static void main(String[] args) {
    greetUser("Aung");
    int total = calculateTotal(20, 3);
    System.out.println("Total: " + total);

    int count = 5;
    tryToReset(count);
    System.out.println("count is still " + count);

    int[] prices = {100, 250};
    doubleFirst(prices);
    System.out.println("prices = " + Arrays.toString(prices));
  }
}

Code breakdown

  1. void methodstatic void greetUser(String name) {

    void means nothing is returned; the job is just to print. name is a String parameter, so a call like greetUser(42) is a compile error.

  2. Returning a valuereturn price * quantity;

    Multiplying two ints gives an int, matching the int return type. The caller catches the 60 with int total = calculateTotal(20, 3);.

  3. Changing a primitive copycount = 0;

    This count is a copy of main's count; sharing the name is a coincidence. Setting the copy to 0 leaves main's count at 5.

  4. Changing through a copied referencevalues[0] = values[0] * 2;

    values is a copy of the reference to the prices array. Both copies point at the same array, so main sees this change as [200, 250].

  5. Calling from maintryToReset(count);

    The call sends the value 5, not the variable itself. That is why the next line prints "count is still 5".

You should see
Hello, Aung!
Total: 60
count is still 5
prices = [200, 250]

What happens when you reassign a copied reference

Assigning a new array to an array parameter only makes the method's local copy point somewhere new. The caller's variable keeps pointing at the old array. Compare replace() with fill() below; it is the simplest experiment that disproves "Java is pass-by-reference".

text
Two references, one array
-------------------------
main:   data   ----+
                   |
                   v
                 [ 0 , 0 ]   <-- fill() writes here: caller sees it
                   ^
fill:   values ----+

replace: values ----> [ 9 , 9 ]  (new array, caller never sees it)
Main.java
import java.util.Arrays;

public class Main {
  static void replace(int[] values) {
    values = new int[] {9, 9}; // the local copy now points to a new array
    values[0] = 1;
  }

  static void fill(int[] values) {
    values[0] = 1; // follows the copied reference to the caller's array
  }

  public static void main(String[] args) {
    int[] data = {0, 0};
    replace(data);
    System.out.println("after replace: " + Arrays.toString(data));
    fill(data);
    System.out.println("after fill:    " + Arrays.toString(data));
  }
}

The output is after replace: [0, 0] and after fill: [1, 0]. Immutable objects such as String and Integer have no methods that modify them, so nothing a method does can change the caller's value; return the new result instead.

In real projects

Where this shows up in real projects

In production code each method owns one job: calculateShipping(), isValidEmail(), formatInvoiceNumber() and so on. Small methods like these are easy to unit test: pass an input, check the return value. "Pure" methods that compute a return value only from their parameters, without touching fields or a database, are the easiest of all to test.

Understanding pass-by-value matters in code review. Hand a List or an array to a helper method and that method can change the data inside it, which causes hard-to-trace bugs when the caller does not expect it. So most teams make it obvious from the name whether a method mutates (sortInPlace) or returns a fresh copy (sorted), and prefer returning new data when mutation is not needed. Java's own standard library uses both styles: Arrays.sort() changes the array, while stream().sorted() gives back a new sequence.

Common mistakes

Common mistakes

1. Missing a return on one path

static int sign(int n) { if (n > 0) return 1; else if (n < 0) return -1; } fails with "missing return statement". The n == 0 path returns nothing, and the compiler does not reason that the two conditions cover every case. Add a final return 0;.

2. Throwing the return value away

calculateTotal(20, 3); on its own compiles, but the 60 is discarded. The same happens with name.toUpperCase(); — the String does not change. Store the result in a variable.

3. Expecting a reassigned parameter to update the caller

Writing tryToReset(count), or values = new int[] {...}, and expecting the caller to change. Parameters are copies; return the new value and let the caller assign it, as in int count = reset();.

Best practices

Best practices

  • Start method names with a verb (calculateTotal, sendEmail) and phrase boolean methods as questions (isValid, hasStock).
  • When a method grows past one screen it usually mixes two jobs; split it.
  • If a method mutates its argument, say so clearly in its name or a comment; when you can return a fresh result instead of mutating, prefer that.

Mini challenge

Mini challenge: grade helper methods

Write three methods for a class's scores, then print the average and grade before and after a bonus.

  • average(int[] scores) returns a double, and 0.0 for an empty array
  • letterGrade(double average) returns A for 80+, B for 65+, C for 50+, otherwise F
  • curve(int[] scores, int bonus) is void, changes the array in place and caps scores at 100
  • main uses {72, 95, 58} and prints the results before and after curving
Main.java
import java.util.Arrays;

public class Main {
  static double average(int[] scores) {
    // TODO: return 0.0 for an empty array, otherwise sum / length as a double
  }

  static String letterGrade(double average) {
    // TODO: A for 80+, B for 65+, C for 50+, otherwise F
  }

  static void curve(int[] scores, int bonus) {
    // TODO: add bonus to every score in place, never above 100
  }

  public static void main(String[] args) {
    int[] scores = {72, 95, 58};
    // TODO: print average + grade, curve by 10, print the array, average + grade
  }
}

Expected: Before: 75.0 -> B Curved: [82, 100, 68] After: 83.33 -> A Empty class: 0.0

Show hint

Dividing an int sum by the length drops the decimals, so cast first: (double) sum / scores.length. Inside curve(), write Math.min(100, score + bonus) back into scores[i]; the change goes through a copied reference, so main sees it.

Show solution
Main.java
import java.util.Arrays;

public class Main {
  static double average(int[] scores) {
    if (scores.length == 0) {
      return 0.0;
    }
    int sum = 0;
    for (int score : scores) {
      sum += score;
    }
    return (double) sum / scores.length;
  }

  static String letterGrade(double average) {
    if (average >= 80) return "A";
    if (average >= 65) return "B";
    if (average >= 50) return "C";
    return "F";
  }

  static void curve(int[] scores, int bonus) {
    for (int i = 0; i < scores.length; i++) {
      scores[i] = Math.min(100, scores[i] + bonus);
    }
  }

  static double round2(double value) {
    return Math.round(value * 100) / 100.0;
  }

  public static void main(String[] args) {
    int[] scores = {72, 95, 58};
    double before = average(scores);
    System.out.println("Before: " + round2(before) + " -> " + letterGrade(before));

    curve(scores, 10);
    double after = average(scores);
    System.out.println("Curved: " + Arrays.toString(scores));
    System.out.println("After: " + round2(after) + " -> " + letterGrade(after));
    System.out.println("Empty class: " + average(new int[0]));
  }
}

Quick quiz 1 / 3

Given static void bump(int n) { n = n + 1; }, what does int x = 4; bump(x); System.out.println(x); print?

Quick quiz 2 / 3

Which method fails with "missing return statement"?

Quick quiz 3 / 3

Given static void clear(int[] a) { a[0] = 0; a = new int[3]; }, what is Arrays.toString(d) after int[] d = {7, 8}; clear(d);?

What to remember

  • A method header has a return type, a name and a typed parameter list; arguments match parameters by position.
  • A non-void method must return on every path, and return ends the method immediately.
  • Java is always pass-by-value: it copies the value for primitives and the reference for objects and arrays.
  • Changes made through a copied reference reach the caller; reassigning the parameter does not.

Java Language Specification, Java SE 25 — Oracle

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Methods | Thuta Learning