JAVA TUTORIAL

Java Intro Java Features Java vs C++ Java Simple Program Java Applet vs Application JVM,JDK or JRE Java Keywords Java Variables Java Literals Java Separators Java Datatypes Java Operators Java Statements Java Array Java String

CONTROL STATEMENTS

Java If-else Java While Loop Java Do-While Loop Java For Loop Java For-each Loop Java Switch Java Break/Continue

JAVA METHODS

Java Method Java Overloading Java Overriding

JAVA CLASSES

Java OOPs Java Classes/Objects Java Inheritance Java Polymorphism Java Encapsulation Java Abstraction Java Modifiers Java Constructors Java Interface Java static keyword Java this keyword

Java Method Overloading

The Java programming language supports overloading methods, and Java can distinguish between methods with different method signatures. This means that methods within a class can have the same name if they have different parameter lists

Overloaded functions have the same name but different types of arguments or parameters assigned to them. They can be used to calculate mathematical or logical operations within the number of assigned variables in the method.

Working of Function Overloading

Function overloading works by calling different functions having the same name, but the different number of arguments passed to it. There are many coding examples that can be shown in order to identify the benefits and disadvantages of function overloading properly.

Example:

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

Example: Add two number of different Data types

public class Simple {
    static int addMethod(int x, int y) {
        return x + y;
    }

    static float addMethod(float x, float y) {
        return x + y;
    }

    public static void main(String[] args) {
        int myNum1 = addMethod(3, 5);
        float myNum2 = addMethod(2.3f, 5.26f);
        System.out.println("int: " + myNum1);
        System.out.println("float: " + myNum2);
    }
}

Output:

int: 8
double: 7.5600004

Example 2: Methods with same name but different types of parameters

class Simple
{
    void sum (int a, int b)
    {
        System.out.println("Sum is: "+(a+b)) ;
    }

    void sum (double a, double b)
    {
        System.out.println("Sum is: "+(a+b));
    }

    public static void main (String[] args)
    {
        Calculate  cl = new Calculate();
        cl.sum (2,5);      //sum(int a, int b) is method is called.
        cl.sum (2.6, 3.3); //sum(double a, double b) is called.
    }
}

Output:

Sum is: 7
Sum is: 5.9

Advantage of Function Overloading

Function overloading works with the same name. So we do not have to create methods that have the same thing as work that is done inside a respective function. The functionality not only resolves the problem of conflicting naming but also improves the readability of the program.