AI Hints
Home›Java Tutorial›Overloading, Scope and Pass by Value
Java · Lesson 58 of 120

Overloading

Same name, different inputs.

⏱ 2 min read▶ Video at 1:12:39🎓 Free
Watch this lesson in the Java courseWatch on YouTube ↗Full Java course

Println works with text, numbers, and booleans. That's because there are several println methods, with the same name, but different parameters. That's called overloading.

  • One name
  • Different parameters
  • Called overloading

Three adds

We have three methods, all called add. One takes two ints, one takes three ints, and one takes two doubles. Java picks the right one, by looking at the arguments. Run it. Five, nine, and three point seven five.

Main.javajava
public class Main {
    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;
    }

    public static void main(String[] args) {
        System.out.println(add(2, 3));
        System.out.println(add(2, 3, 4));
        System.out.println(add(1.5, 2.25));
    }
}
Output
5
9
3.75

Overloading rules

Overloaded methods must differ in their parameters, the number, or the types. A different return type alone isn't enough. Use overloading for methods that do the same job, with different inputs.

keyvalue
Samemethod name
Differentnumber or types of parameters
Not enoughonly a different return type
Exampleprintln(int), println(String)

Summary

Overloading means several methods with one name, but different parameters. Java picks the one that matches. Next, where variables live, called scope.

Key takeaways
  • Same name
  • Different parameters
  • Java picks the match
Next up: Scope — where a variable lives