Jimmy M Jimmy M - 1 month ago 10
Java Question

How does this overloading work?

class OverloadingTEsting
{
public static void foo(int m,long n)
{
System.out.println("int m,long n");
}
public static void foo(int i,int j)
{
System.out.println("int i,int j ");
}

public static void main(String args[])
{
foo('A',5);

}
}


The output i am getting is (int i, int j)
Shouldn't this be a error because parameter has a A??
i am a beginner to overloading
What did the parameters go into the second method?

Answer

char 'A' is converted into the int value that the specified Unicode character represents (which is 65). And Number 5 is treated as integer by default, so foo(int i,int j) is being invoked.

To invoke the long version, you can change to foo('A',5L) or foo('A',5l) (i.e., suffixing the number with uppercase L or lowercase l) or by passing a long datatype variable as second argument.

Also, for your understanding, to find the numeric representation of any character ('A', 'B', 'C', etc..), you can use the 'getNumericValue' method from Character class:

public static int getNumericValue(char ch)

Returns the int value that the specified Unicode character represents. For example, the character '\u216C' (the roman numeral fifty) will return an int with a value of 50.

Please refer the character api below: https://docs.oracle.com/javase/8/docs/api/java/lang/Character.html

Comments