• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

choosing method

 
Prabhu Venkatachalam
Ranch Hand
Posts: 502
Java jQuery Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class GFC215 {
static String m(float i) {return "float";}
static String m(double i) {return "double";}
public static void main (String[] args) {
int a1 = 1; long b1 = 2;
System.out.print(m(a1)+","+ m(b1));
}}

Ans is : float,float

can anybody explain this?
 
Chandrakanth
Ranch Hand
Posts: 60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
--------------------------------------------------------------------------------
class GFC215 {
static String m(float i) {return "float";}
static String m(double i) {return "double";}
public static void main (String[] args) {
int a1 = 1; long b1 = 2;
System.out.print(m(a1)+","+ m(b1));
}}

Ans is : float,float

can anybody explain this?

The answer is float, float is perfect.

you need to have a background on how the overloaded methods are called based on the parameters.

whenever you are calling a overloaded method with a parameter, the compiler will check for the method with the type of the parameter you are passing, if the method is not found it will uppercast the parameter and then try to find the method that match.

now for this eg. conversion goes like this

int is first converted to long but compiler not able to find the method so long inturn is converted to float and method is searched. so output is float
smilarly for long
long -> float method found and so output is float
 
Sasikanth Malladi
Ranch Hand
Posts: 175
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Also see this thread: Method Overloading
Sashi
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic