Tutorials References Exercises Videos Menu
Free Website Get Certified Pro

Java Tutorial

Java HOME Java Intro Java Get Started Java Syntax Java Output Java Comments Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Math Java Booleans Java If...Else Java Switch Java While Loop Java For Loop Java Break/Continue Java Arrays

Java Methods

Java Methods Java Method Parameters Java Method Overloading Java Scope Java Recursion

Java Classes

Java OOP Java Classes/Objects Java Class Attributes Java Class Methods Java Constructors Java Modifiers Java Encapsulation Java Packages / API Java Inheritance Java Polymorphism Java Inner Classes Java Abstraction Java Interface Java Enums Java User Input Java Date Java ArrayList Java LinkedList Java HashMap Java HashSet Java Iterator Java Wrapper Classes Java Exceptions Java RegEx Java Threads Java Lambda

Java File Handling

Java Files Java Create/Write Files Java Read Files Java Delete Files

Java How To

Add Two Numbers

Java Reference

Java Keywords Java String Methods Java Math Methods

Java Examples

Java Examples Java Compiler Java Exercises Java Quiz Java Certificate


Java Method Overloading


Method Overloading

With method overloading, multiple methods can have the same name with different parameters:

Example

int myMethod(int x)
float myMethod(float x)
double myMethod(double x, double y)

Consider the following example, which has two methods that add numbers of different type:

Example

static int plusMethodInt(int x, int y) {
  return x + y;
}

static double plusMethodDouble(double x, double y) {
  return x + y;
}

public static void main(String[] args) {
  int myNum1 = plusMethodInt(8, 5);
  double myNum2 = plusMethodDouble(4.3, 6.26);
  System.out.println("int: " + myNum1);
  System.out.println("double: " + myNum2);
}

Try it Yourself »

Instead of defining two methods that should do the same thing, it is better to overload one.

In the example below, we overload the plusMethod method to work for both int and double:

Example

static int plusMethod(int x, int y) {
  return x + y;
}

static double plusMethod(double x, double y) {
  return x + y;
}

public static void main(String[] args) {
  int myNum1 = plusMethod(8, 5);
  double myNum2 = plusMethod(4.3, 6.26);
  System.out.println("int: " + myNum1);
  System.out.println("double: " + myNum2);
}

Try it Yourself »

Note: Multiple methods can have the same name as long as the number and/or type of parameters are different.