Java Basics, Java Programming · December 2, 2026

Java for Beginners, Lesson 25: Methods and Method Overloading in Java

Java for Beginners · Module 5: Data and Methods


🎯 Why Methods?

You have written all your code inside main so far. Long programs written that way become impossible to read. A method is a named block of code that does one job. You write it once and call it as many times as you like, from anywhere.

📌 A method has a name, optional parameters (inputs) and a return type (output). It runs only when called. Methods make code shorter, reusable and easier to test.

1️⃣ Writing and Calling Methods

static int square(int n) {
    return n * n;
}
static belongs to the class  |  int return type  |  square name  |  int n parameter  |  return sends a value back

Figure 1: The parts of a method.

  • Return type: the type of value the method gives back. Use void when it gives back nothing.
  • Parameters: the inputs, each with a type and a name, in brackets.
  • return: sends a value back and ends the method immediately.
  • static: for now, write static on every method you call from main. Lesson 29 explains why.

Program 1: Four small methods

public class MethodBasics {
    static void greet() {
        System.out.println("Hello from a method!");
    }

    static int square(int n) {
        return n * n;
    }

    static double average(int a, int b, int c) {
        return (a + b + c) / 3.0;
    }

    static boolean isEven(int n) {
        return n % 2 == 0;
    }

    public static void main(String[] args) {
        greet();
        greet();
        System.out.println("square(7) = " + square(7));
        int r = square(4) + square(3);
        System.out.println("4^2 + 3^2 = " + r);
        System.out.println("average = " + average(70, 80, 90));
        System.out.println("isEven(10) = " + isEven(10));
    }
}
🖥️ Output:
Hello from a method!
Hello from a method!
square(7) = 49
4^2 + 3^2 = 25
average = 80.0
isEven(10) = true
  • greet() is called twice and runs twice: write once, use many times.
  • A method that returns a value can be used inside an expression: square(4) + square(3).
  • The values you pass when calling (7, 70, 80, 90) are arguments. They fill the parameters (n, a, b, c) in order.
  • Execution starts in main, jumps into a method when it is called, and comes back to the next line when the method ends.

2️⃣ Pass by Value

int n = 5
main
copy of 5 ➜
x becomes 99
inside the method
back in main
n is still 5
int[] a
main: reference R
copy of R ➜
arr also points to R
arr[0] = 99 changes the shared array
back in main
a[0] is 99

Figure 2: Java passes a copy of the value. For arrays and objects, the copy is of the reference.

When you call a method, Java gives it a copy of each argument. For primitives, changing the copy cannot affect the original. For arrays and objects the copy is a copy of the reference, so the method can change the shared array, but it cannot make the caller’s variable point somewhere else.

import java.util.Arrays;

public class PassByValue {
    static void changeNumber(int x) {
        x = 99;
        System.out.println("inside changeNumber: x = " + x);
    }

    static void changeArray(int[] arr) {
        arr[0] = 99;
    }

    static void reassignArray(int[] arr) {
        arr = new int[]{7, 7, 7};
    }

    public static void main(String[] args) {
        int n = 5;
        changeNumber(n);
        System.out.println("after changeNumber: n = " + n);

        int[] a = {1, 2, 3};
        changeArray(a);
        System.out.println("after changeArray: " + Arrays.toString(a));
        reassignArray(a);
        System.out.println("after reassignArray: " + Arrays.toString(a));
    }
}
🖥️ Output:
inside changeNumber: x = 99
after changeNumber: n = 5
after changeArray: [99, 2, 3]
after reassignArray: [99, 2, 3]
  • n stays 5: the method changed only its own copy x.
  • changeArray changed the real array, because both names point to the same array (Lesson 21).
  • reassignArray pointed its own copy of the reference at a new array. The caller’s a still points to the old one, so nothing changed.
  • So Java is always pass by value. With objects, the value passed is the reference.

3️⃣ Method Overloading

Several methods may share one name if their parameter lists differ (in number, type or order). This is called overloading. Java picks the best match from the arguments you give.

CallChosen methodWhy
add(2, 3)add(int, int)exact match
add(2, 3, 4)add(int, int, int)three arguments
add(2.5, 3.5)add(double, double)decimals
add("Ja", "va")add(String, String)text
add(2, 3.5)add(double, double)int is widened to double
add(b, b) (bytes)add(int, int)byte is widened to int

Figure 3: How Java picks an overloaded method.

public class Overload {
    static int add(int a, int b) {
        return a + b;
    }

    static int add(int a, int b, int c) {
        return a + b + c;
    }

    static double add(double a, double b) {
        return a + b;
    }

    static String add(String a, String b) {
        return a + b;
    }

    public static void main(String[] args) {
        System.out.println(add(2, 3));
        System.out.println(add(2, 3, 4));
        System.out.println(add(2.5, 3.5));
        System.out.println(add("Ja", "va"));
        System.out.println(add(2, 3.5));
        byte b = 1;
        System.out.println(add(b, b));
    }
}
🖥️ Output:
5
9
6.0
Java
5.5
2
  • This is how println accepts an int, a double, a String and more under one name.
  • When there is no exact match, Java widens the arguments (Lesson 9): add(2, 3.5) uses the double version.
  • The return type alone does not make an overload. The parameter list must differ.

4️⃣ Varargs and Early return

public class Varargs {
    static int sum(int... numbers) {
        int total = 0;
        for (int n : numbers) {
            total += n;
        }
        return total;
    }

    static String describe(String label, int... values) {
        return label + " has " + values.length + " values";
    }

    static int maxOf(int a, int b) {
        return (a > b) ? a : b;
    }

    static void printStars(int n) {
        if (n <= 0) {
            return;
        }
        for (int i = 0; i < n; i++) System.out.print("*");
        System.out.println();
    }

    public static void main(String[] args) {
        System.out.println(sum());
        System.out.println(sum(5));
        System.out.println(sum(1, 2, 3, 4));
        System.out.println(describe("scores", 90, 80));
        System.out.println(maxOf(maxOf(3, 9), 5));
        printStars(5);
        printStars(-1);
        printStars(3);
    }
}
🖥️ Output:
0
5
10
scores has 2 values
9
*****
***
  • int... numbers (varargs) accepts any number of ints, including none. Inside the method, numbers is an ordinary array. The varargs parameter must be the last one.
  • Methods can call other methods: maxOf(maxOf(3, 9), 5) finds the largest of three.
  • In a void method, a bare return; leaves early. printStars(-1) prints nothing.

5️⃣ Errors Beginners Meet

Wrong arguments

public class Bad1 {
    static int twice(int n) {
        return n * 2;
    }

    public static void main(String[] args) {
        int x = twice("5");
        twice(1, 2);
        String s = twice(3);
    }
}
🖥️ Compiler message:
Bad1.java:7: error: incompatible types: String cannot be converted to int
int x = twice(“5”);
^
Bad1.java:8: error: method twice in class Bad1 cannot be applied to given types;
twice(1, 2);
^
required: int
found: int,int
reason: actual and formal argument lists differ in length
Bad1.java:9: error: incompatible types: int cannot be converted to String
String s = twice(3);
^
3 errors
  • The method expects one int and returns an int. Check the count and types of your arguments and what you store the result in.

A path with no return

public class Bad4 {
    static int sign(int n) {
        if (n > 0) {
            return 1;
        }
    }

    public static void main(String[] args) {
        System.out.println(sign(5));
    }
}
🖥️ Compiler message:
Bad4.java:6: error: missing return statement
}
^
1 error
  • If n is not positive, the method reaches the end without returning anything. Add a return for the other cases.

Overloading by return type only

public class Bad2 {
    static int add(int a, int b) {
        return a + b;
    }

    static double add(int a, int b) {
        return a + b;
    }

    public static void main(String[] args) {
        System.out.println(add(1, 2));
    }
}
🖥️ Compiler message:
Bad2.java:6: error: method add(int,int) is already defined in class Bad2
static double add(int a, int b) {
^
1 error

Calling an instance method from main

public class Bad3 {
    void hello() {
        System.out.println("hi");
    }

    public static void main(String[] args) {
        hello();
    }
}
🖥️ Compiler message:
Bad3.java:7: error: non-static method hello() cannot be referenced from a static context
hello();
^
1 error
  • main is static, so it can call only static methods directly. Add static for now. Lesson 29 shows the other way, with objects.

⚠️ Common Mistakes

MistakeProblemFix
Forgetting static on a helper called from mainnon-static method errorAdd static
Not returning on every pathmissing return statementReturn in every branch
Ignoring the returned valueResult thrown awayStore it or print it
Expecting a method to change a primitive argumentIt only changes a copyReturn the new value
Overloading with only a different return typeAlready definedChange the parameters
Arguments in the wrong orderWrong result, no error if types matchCheck parameter order

❓ Frequently Asked Questions

Q1. What is the difference between a parameter and an argument?
A parameter is the variable in the method definition. An argument is the actual value you pass when calling.

Q2. Can a method return more than one value?
Not directly. Return an array or an object, or split the work into separate methods.

Q3. Is Java pass by reference?
No. It is always pass by value. For objects the value copied is the reference, which is why a method can change the object but cannot re-point the caller’s variable.

Q4. Why is main static?
The JVM must call it before any object exists (Lesson 5).

✅ Key Takeaways

  • A method has a return type, a name, parameters and a body. void means no return value.
  • Arguments fill parameters in order. return sends a value back and ends the method.
  • Java passes copies of values. A method cannot change a caller’s primitive.
  • Overloading: same name, different parameter lists. The return type alone is not enough.
  • int... x accepts any number of arguments and behaves as an array.
🎓 Practice questions: (1) Write a method isPrime(int n) that returns a boolean, and use it to print the primes up to 30. (2) Write overloaded methods area for a circle, a rectangle and a square. (3) Write a method that returns the largest element of an int[]. (4) Why does a swap method swap(int a, int b) not swap the caller’s variables? (5) Write a varargs method that returns the average of its arguments.
All 30 lessons in this series (open course page)

Module 1 · Getting Started

Module 2 · Building Blocks

Module 3 · Operators

Module 4 · Control Flow

Module 5 · Data and Methods

Module 6 · Objects and Revision