Curriculum
Course: Java Basic
Login

Curriculum

Java Basic

Java Home

0/1

Java Introduction

0/1

Java Get Started

0/1

Java Syntax

0/1

Java Comments

0/1

Java Type Casting

0/1

Java Operators

0/1

Java Booleans

0/1

Java Switch

0/1

Java Break / Continue

0/1

Java Errors and Exception

0/1
Text lesson

Java Method Overloading

Method Overloading

Method overloading allows for the creation of multiple methods that share the same name but have different parameters.

Example

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

Take a look at this example, where there are two methods for adding numbers of different types:

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);
}

Instead of creating separate methods for similar tasks, it’s more efficient to overload one method.

In the example provided, we demonstrate overloading the plusMethod to handle both int and double types:

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);
}

 

Please note that it’s permissible for multiple methods to share the same name as long as the parameters’ number and/or types differ.