File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Overloaded Methods vs. Ppcasting. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Overloaded Methods vs. Ppcasting." Watch "Overloaded Methods vs. Ppcasting." New topic

Overloaded Methods vs. Ppcasting.

Arsin Delve

Joined: Jul 08, 2001
Posts: 29
I'm not clear on what will happen if I have two overloaded methods such as
public void thisMethod (int i) {}
public void thisMethod (float f) {}
How does it choose which method to run when my argument is say a short or a byte? For that matter, if my arguement is an int, either method should accept this. How does the VM make this distinction?
It could get very complicated if I have more than one argument. Example:
Let's say I have:
void aMethod (float f, double d)
void aMethod (long l, float f)
If I make a call with an int and a float, or a short and a long, what happens?

I hope I have explained myself well. Thank you in advance for your help.
Arsin Delve.

Manfred Leonhardt
Ranch Hand

Joined: Jan 09, 2001
Posts: 1492
Hi Arsin,
According to the JVM specs:

Where an actual argument expression corresponding to a parameter variable is not FP-strict, evaluation of that actual argument expression is permitted to use values drawn from the appropriate extended-exponent value sets. Prior to being stored in the parameter variable, the result of such an expression is mapped to the nearest value in the corresponding standard value set by method invocation conversion.

What this means is that the following is used to figure out which to method signature matches:
byte -> short -> integer -> long -> float -> double
The exception: char -> integer
For example: public void Method( int i )
can be called with:
byte b = 123;
ob.Method( b );
short s = 123;
ob.Method( s );
int i = 123;
ob.Method( i )
Arsin Delve

Joined: Jul 08, 2001
Posts: 29
Thank you for your reply. The only (highly unlikely) case that still remains confused in my mind is the following:

What would result from this method call?
-Arsin Delve

[This message has been edited by Arsin Delve (edited July 08, 2001).]
Vanitha Sugumaran
Ranch Hand

Joined: Apr 11, 2001
Posts: 356
You will get error, since reference to the method is ambiguous.
Thomas Paul
mister krabs
Ranch Hand

Joined: May 05, 2000
Posts: 13974
Often the best way to understand how these things works is to code up a program and give it a spin.

Associate Instructor - Hofstra University
Amazon Top 750 reviewer - Blog - Unresolved References - Book Review Blog
I agree. Here's the link:
subject: Overloaded Methods vs. Ppcasting.
It's not a secret anymore!