Przykładowy Mail
Przykładowy Mail

Reputation: 1

Java - strange task for overloading methods

I have a task which should check if I understand overloading methods...

but this task confused me much more

What is an explanation of this fact?

    bar(i,c);
    bar(l,c);   

Output:

II
DL

Is there any scheme how to solve such tasks, any rule?

public class Foo{

    static void bar(int a, double b){
    System.out.println("ID");
    }

    static void bar(int a, int b){
    System.out.println("II");
    }

    static void bar(double a, long b){
    System.out.println("DL");
    }

    static void bar(float... a){
    System.out.println("FS");
    }

    static void bar(int a, byte b){
    System.out.println("IB");
    }

    static void bar(double a, double b){
    System.out.println("DD");
    }
    public static void main(String[] args) {


        int i=0;
        long l =0;
        float f=0;
        double d=0;
        char c='0';
        bar(i,f);
        bar(d,i);
        bar(i,c,i);
        bar(i,c);
        bar(l,c);

    }

}

Upvotes: 0

Views: 66

Answers (2)

imps
imps

Reputation: 1661

From https://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html#jls-5.1.2

19 specific conversions on primitive types are called the widening primitive conversions:

byte to short, int, long, float, or double

short to int, long, float, or double

char to int, long, float, or double

int to long, float, or double

long to float or double

float to double

A widening primitive conversion does not lose information about the overall magnitude of a numeric value.

Basically since there's no long/char signature it will try to promote them to the above types and make decision based on that. There's a fairly elaborate algorithm here:

http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.12

And more specifically here:

http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.12.2

Upvotes: 0

Bathsheba
Bathsheba

Reputation: 234655

If there is a function that takes a long as a parameter and there is not one taking a long, and an int is supplied, then that int is promoted automatically to a long type.

If there is a function that takes a double as a parameter and there is not one taking a double, and a long is supplied, then that long is promoted automatically to a double type. Note that this conversion can cause you to lose precision: not all integers over the 53rd power of 2 can be represented exactly in a double.

These rules, of course, generalises to functions taking more than one parameter and explain the output your are observing.

Upvotes: 1

Related Questions