• 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Liutauras Vilda
  • Bear Bibeault
Sheriffs:
  • Jeanne Boyarsky
  • Tim Cooke
  • Devaka Cooray
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Piet Souris
  • salvin francis
  • Stephan van Hulst
Bartenders:
  • Frits Walraven
  • Carey Brown
  • Jj Roberts

choosing method

 
Ranch Hand
Posts: 502
jQuery Spring Java
  • 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?
 
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
 
Ranch Hand
Posts: 175
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Also see this thread: Method Overloading
Sashi
 
What a show! What atmosphere! What fun! What a tiny ad!
Thread Boost feature
https://coderanch.com/t/674455/Thread-Boost-feature
reply
    Bookmark Topic Watch Topic
  • New Topic