• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

choosing method

 
Ranch Hand
Posts: 502
jQuery Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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?
 
Ranch Hand
Posts: 60
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Ranch Hand
Posts: 175
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Also see this thread: Method Overloading
Sashi
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic