File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes choosing method Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Head First Android this week in the Android forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "choosing method" Watch "choosing method" New topic
Author

choosing method

Prabhu Venkatachalam
Ranch Hand

Joined: Nov 16, 2005
Posts: 502

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?


Prabhu Venkatachalam<br />SCJP 1.4,SCWCD 1.4<br />prabhu.venkatachalam@gmail.com
Chandrakanth
Ranch Hand

Joined: Aug 16, 2005
Posts: 60
--------------------------------------------------------------------------------
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

Joined: Nov 04, 2000
Posts: 175
Also see this thread: Method Overloading
Sashi
 
Don't get me started about those stupid light bulbs.
 
subject: choosing method
 
jQuery in Action, 3rd edition