Google

Friday, May 11, 2007

Method Overloading with new features of Java 1.5

I was playing with Autoboxing and Ver-args features of Java 1.5 and found interesting results with method overloading.

If you have a class which has a method void hello(Integer x) and you call hello(5) then Autoboxing will come into play may and method hello will be called.

Another case is, If you have a method void hello(long x) and you call
hello(5) then primitive integer 5 will be widened to long and method hello will be called.

Now suppose you have hello method overloaded in your class. Lets look at this example in detail.

public class methodOverloading{
public static void hello(Integer x){System.out.println("Integer");}
public static void hello(long x){System.out.println("long");}
public static void main(String[] args){
int i = 5;
hello(i);
}
}

Guess what would be output when we execute this java program. One can imagine of two answers. If you think Autoboxing will be done then "Integer" would be printed. But if you think widening of integer will take place then "long" would be printed. The only reason is, Sun did not want already existing programs to get different results, when they switch to Java 1.5. With earlier Java versions, widening would have taken place and long would have been printed, so is happening with Java 1.5 as well.

The question is, given that both methods exist, which one will be used? In other words, which one compiler think more desirable, Autoboxing or widening? The answer is that the compiler will choose widening over boxing, so the output would be "long".

Compiler can choose to perform following three operations
  • Widening
  • Autoboxing
  • Var-args

At any point in time there are two possible options like in above example then compiler would choose; "Widening over Autoboxing", "Widening over Var-args", "Autoboxing over Var-args".

Now the question is, what if there is a combination of these operations required? To get an answer of this question one needs to understand how widening works with objects. Widening in objects only in IS-A relation. If class Horse extends Animal then Horse can be widened to Animal for that reason any class can be widened to Object. Can Integer be widened to Long? Answer is NO because there is no IS-A relation there.

When there is a combination of operations required compiler will perform BoxingAndWidening but it will not perform WideningAndBoxing. It is just too much work for the compiler.

class WidenAndBox{
static void go(Long x){
System.out.println("This is from long");
}
public static void main(String[] args){
byte b = 5;
go(b);
}
}

Here Compiler needs to Widen byte to long first and then It can be boxed to Long which is not allowed (Searching for reason, Any references are welcome).

class BoxAndWiden{
static void go(Object x){
System.out.println("This is from object");
}
public static void main(String[] args){
byte = 5;
go(b);
}
}

Here compiler needs to be boxed into Byte first and then can be widen to Object because it follows IS-A relation.

This is it from my side. Feel free to share your ideas on this.

Labels: , , , , ,

34 Comments:

At March 23, 2008 at 10:19 PM , Blogger deepak said...

It is good...

 
At July 16, 2008 at 1:10 AM , Anonymous Anonymous said...

Hi! its good..
but the topic is not covered thoroughtly...

you have explained that complier choose "BoxingAndThenWidening" if it is needed..

but what if i have a two methods like

public void test(Integer... x){ }
public void test(Number n1, Number 2){ }

and invoking the method
test(1, 2)

so what complier will choose??
"BoxingAndWidening" or "BoxingAndVarArgs" ???????

--------------------------

another scenario:
public void test(int... x){ }
public void test(Number n1, Number n2){ }

and calling...
test(1, 2);

what will compiler choose;
"WideningAndVarArgs" or "BoxingAndWidening"

----------------------------

another scenario:

public void test(int... x){ }
public void test(Number... x){ }

and calling...
test(1, 2);

will it compile??? successfully??
and if compiled then which method will be invoked???
in short, "BoxingAndWindeningAndVarArgs" or "WideningAndVarArgs" ????

 
At December 27, 2009 at 9:30 PM , Anonymous Anonymous said...

Brim over I acquiesce in but I think the post should have more info then it has.

 
At January 14, 2010 at 10:38 AM , Anonymous Anonymous said...

I wish not acquiesce in on it. I assume warm-hearted post. Specially the title-deed attracted me to study the whole story.

 
At January 18, 2010 at 6:51 AM , Anonymous Anonymous said...

Nice dispatch and this enter helped me alot in my college assignement. Thanks you on your information.

 
At January 28, 2010 at 9:55 AM , Anonymous Anonymous said...

[url=http://vegasonlines.net/online-casino-affiliate-program.html]casinos de la provincia de cordoba [/url]
[url=http://vegasonlines.net/computer-games-casino.html]salsa casino [/url]
[url=http://vegasonlines.net/lake-charles-casino.html]casino costa blanca [/url]
[url=http://vegasonlines.net/bwin-casino.html]borgatta casino atlantic city [/url]
[url=http://vegasonlines.net/borgata-casino-and.html]atlantic city casino show [/url]
[url=http://vegasonlines.net/casino-phoenix-arizona.html]casino online cn bonus [/url]
[url=http://vegasonlines.net/casino-orillia-ontario.html]casino video poker [/url]
[url=http://vegasonlines.net/casino-no-deposit-no.html]best no deposit casino bonuses [/url]
[url=http://vegasonlines.net/hard-rock-casino-fort-lauderdale.html]juegos de casino para descargar [/url]
[url=http://vegasonlines.net/punta-cana-casino-resort.html]descarga juego on line casino gratis [/url]
[url=http://vegasonlines.net/cyber-casino.html]casino slot game [/url]
[url=http://vegasonlines.net/mystic-lake-casino-minnesota.html]casino descarga online [/url]
[url=http://vegasonlines.net/hollywood-casino-tunica.html]comprar dvd baile salsa rueda casino [/url]
[url=http://vegasonlines.net/casino-argosy.html]reno silver legacy resort casino [/url]
[url=http://vegasonlines.net/casino-for-fun.html]mueble juego casino [/url]
ocio juego casino
[b]steve wynn casino[/b]
10 best online casino
casino aranjuez actuacion
[b]playas de casino brasil[/b]
casino estoril portugal
[u]casino bahia cadiz[/u]
jeux casino sur net
aladdin resort and casino home page
[b]internet casino gambling game[/b]
catarata niagara bear den at seneca niagara casino
casino online american casino

 
At January 29, 2010 at 9:55 AM , Anonymous Anonymous said...

[url=http://seghan.ru/go.php?sid=35][img]http://s002.radikal.ru/i200/1001/f0/0ddd2280d906.jpg[/img][/url]












[url=http://vonzura.misslich.de/sitemap.html]and buy cigarettes [/url]
buy roll in cigarette filter tips camel cigarettes reynolds mail order to buy cheap cigarette
[url=http://deuaexj.naheliegend.de/]age to buy cigaretts [/url]
cigarette buying age buy cheap cigarette newport buy cigarettes from south carolina
[url=http://botziho.485.at/sitemap.html]buy marlboro cigarette [/url]
where can i buy davidoff cigarettes zibb cigarettes buy buy cigarettes paypal
[url=http://deuaexj.naheliegend.de/]buy cigarettes cheap online [/url]
buy cigarettes at a buy cigarettes online illinois buy cigarettes over the world
[url=http://deuaexj.naheliegend.de/]red apple cigarettes buy [/url]
buy epique cigarettes buying cigarettes in virginia where to buy quest cigarettes
[url=http://powjxun.wieder-mal.de/sitemap.html]buy indian cigarettes ontario [/url]
buying and cigarettes or tobacco and law order cigarettes from new york buy cigarettes on internet
[url=http://mlwqdwu.xn--baldmglichst-8ib.de/]where can i buy candy cigarettes [/url]
buy cigarettes at 16 buy cigarettes online legally buy hassan cigarette cards
[url=http://ubpscsn.pro.ac/sitemap.html]buy camel blue cigarettes [/url]
zibb cigarettes buy buy cigarettes online native american buy cigarettes online from discount store
[url=http://botziho.485.at/]buy belmont cigarettes online [/url]
buying russian cigarettes on line buy newport cigarettes online by visa buy barclay cigarettes
[url=http://tioozua.connection24.de/sitemap.html]to buy cigarette cases [/url]
how to buy cigarettes cheaper law on buying cigarettes buy some candy and cigarettes

 
At March 9, 2010 at 7:02 PM , Anonymous Anonymous said...

Hello. My wife and I bought our house about 6 months ago. It was a foreclosure and we were able to get a great deal on it. We also took advantage of the 8K tax credit so that definitely helped. We did an extensive remodeling job and now I want to refinance to cut the term to a 20 or 15 year loan. Does anyone know any good sites for mortgage information? Thanks!

Mike

 
At November 24, 2012 at 1:54 PM , Anonymous Anonymous said...

With havin so much content do you ever run into any problems of plagorism or copyright infringement?
My website has a lot of exclusive content I've either authored myself or outsourced but it looks like a lot of it is popping it up all over the internet without my agreement. Do you know any solutions to help reduce content from being stolen? I'd definitely appreciate it.
Visit my web page ; watch nfl online

 
At November 27, 2012 at 9:46 AM , Anonymous Anonymous said...

Hi there! I could have sworn I've visited this blog before but after looking at many of the articles I realized it's new
to me. Anyways, I'm certainly pleased I found it and I'll be book-marking it and checking
back regularly!
Here is my webpage - http://www.youtube.com/

 
At November 27, 2012 at 2:34 PM , Anonymous Anonymous said...

I am really grateful to the owner of this web page who has shared this wonderful paragraph at at this time.
Also see my page > learn piano

 
At November 27, 2012 at 4:53 PM , Anonymous Anonymous said...

Do you mind if I quote a couple of your articles as long
as I provide credit and sources back to your weblog? My
website is in the exact same niche as yours and my users would really benefit from a lot of the information you
present here. Please let me know if this ok with you.
Cheers!
My web site - my computer is slow

 
At December 2, 2012 at 10:55 AM , Anonymous Anonymous said...

I got this site from my pal who informed me on the topic of this web site and now this time I am browsing this website and reading very informative posts at this
place.
Review my page ; http://asuntoturkista.net

 
At December 2, 2012 at 1:39 PM , Anonymous Anonymous said...

Your way of explaining the whole thing in this post is
truly fastidious, every one be able to without difficulty be aware of it, Thanks a
lot.
Review my blog :: mac baren

 
At December 4, 2012 at 3:36 PM , Anonymous Anonymous said...

I absolutely love your blog and find nearly all of your post's to be precisely what I'm looking
for. Does one offer guest writers to write content available for you?
I wouldn't mind composing a post or elaborating on a lot of the subjects you write concerning here. Again, awesome weblog!
Also see my page - www.yourtobaccosstore.com

 
At December 5, 2012 at 9:06 AM , Anonymous Anonymous said...

Oh my goodness! Incredible article dude! Thank you, However I am having troubles with your
RSS. I don't understand why I cannot subscribe to it. Is there anyone else getting the same RSS issues? Anyone that knows the solution can you kindly respond? Thanks!!
Also visit my page diablo 3 guide

 
At December 13, 2012 at 7:35 PM , Anonymous Anonymous said...

My family always say that I am killing my time here at web, except I know I am getting know-how every day by reading
such pleasant content.
Also visit my website ; van nelle

 
At December 14, 2012 at 7:28 AM , Anonymous Anonymous said...

Quality posts is the key to attract the viewers
to pay a visit the web page, that's what this website is providing.
Also see my page > amber leaf

 
At December 14, 2012 at 11:30 PM , Anonymous Anonymous said...

I think this is among the most important information
for me. And i am glad reading your article. But should remark on few general things, The website style is ideal,
the articles is really excellent : D. Good job, cheers
Feel free to visit my site ... samson tobacco

 
At December 16, 2012 at 10:01 PM , Anonymous Anonymous said...

After I originally left a comment I seem to have clicked the -Notify me
when new comments are added- checkbox and now every time a
comment is added I recieve four emails with the exact
same comment. Perhaps there is a way you are able to remove me from that service?
Many thanks!
My webpage - clear acne

 
At December 16, 2012 at 10:05 PM , Anonymous Anonymous said...

Pretty nice post. I just stumbled upon your blog
and wished to say that I've truly enjoyed surfing around your weblog posts. In any case I'll be subscribing for
your feed and I am hoping you write again soon!
Look into my page ; acne products

 
At December 25, 2012 at 5:47 PM , Anonymous Anonymous said...

I've been surfing online greater than 3 hours today, yet I by no means discovered any fascinating article like yours. It's pretty price sufficient for me.

Personally, if all web owners and bloggers made excellent content as you did, the web will likely be much more useful than ever before.
my page: immobilienalanya.net

 
At January 15, 2013 at 11:48 PM , Blogger Unknown said...

Asunto Turkista
Asunto Turkista
Huvilat Turkista
Kiinteistöt Turkista
Koti Turkista
Asunto Alanyasta

immobilien Türkei
immobilien Alanya
Türkei immobilien
villa Türkei
immobilienfirmen türkei

Недвижимость в Турции
купить квартиру в турции
турция алания недвижимость
Квартиры в Турции
Виллы в Турции
земля турции
недвижимость в турции алания махмутлар
Квартиры в Махмутларe
недвижимость в турции алания махмутлар
апартаменты в турции
земли в Турции

makelaars Turkije
appartementen turkije
koopwoningen turkije
leilighet Tyrkia
Bostad Turkiet
Tyrkiet Lejligheder
Tyrkiet Ejendomsmægler

alanya da daire
apartments in turkey
apartments in Avsallar
apartments in turkey
villas in Turkey

 
At January 29, 2013 at 6:07 PM , Anonymous Anonymous said...

top [url=http://www.001casino.com/]free casino bonus[/url] coincide the latest [url=http://www.casinolasvegass.com/]free casino[/url] free no consign perk at the best [url=http://www.baywatchcasino.com/]baywatch casino
[/url].

 
At April 1, 2013 at 8:05 AM , Blogger Unknown said...

Kiinteistö Turkista
Asunto Turkista
Kiinteistö Turkki
Alanyan Kiinteistö
Mahmutlarin Kiinteistö
Loma-asunto
Lomahuoneisto Turkista
Turkki loma asunnot
Alanya asunto
Huvilat Turkissa
Kattohuoneisto Turkissa
Alanya kiinteistönvälitys
Alanya
Turkki
Mahmutlar
Asuntoja Alanya

 
At November 16, 2016 at 6:01 PM , Blogger Nguyễn Lê Hồng thi said...

Thanks for sharing. I tried a few & enjoyed all (Here’s the Thing, Modern Love, Another Round and Mystery Show). huong dan cá cược

 
At June 30, 2017 at 3:17 AM , Blogger Swathi said...

Hi,
Very nice and informative article. Thanks for posting. Keep posting.

http://kosmiktechnologies.com/java-training-institutes-in-kukatpally/

 
At September 15, 2020 at 4:22 AM , Blogger Ontario Security license said...

Shield Security Solutions Offers Security Guard License Training across the province of Ontario. Get Started Today!

Security Guard License | Security License | Ontario Security license | Security License Ontario | Ontario Security Guard License | Security Guard License Ontario

 
At February 4, 2021 at 1:25 AM , Blogger Quikads said...

The explanation is comprehensive and informative.
An LED TV uses less power, provides a brighter display with better contrast, a thinner panel, and lesser heat dissipation than a conventional LCD TV. This is because an এল ই ডি টিভি uses light-emitting diodes for backlighting as opposed to the CCFLs of conventional LCD TVs.

 
At November 11, 2021 at 12:26 PM , Blogger Truck and Trailer said...

The explanation is comprehensive and informative.
Truck Alignment
roadside assistance services
Truck Alignment
Trailer repair near me
Truck towing near me

 
At November 11, 2021 at 12:46 PM , Blogger Self Storage said...

The explanation is comprehensive and informative. moving services near me
commercial movers near me
house movers ontario
self storage company

 
At June 11, 2022 at 2:19 AM , Blogger BIGSTAR V2SERVICES said...

Bigstar V2services Private Ltd is a well-known company that provides Security Services in Bangalore at a reasonable cost to its valued customers. We work with reputable multinational corporations, businesses, industries, banks, warehouses, flats, bungalows, showrooms, and hotels to provide security services. Our security experts are well-trained and dedicated at the time of need to defend our clients' property.

 
At July 31, 2022 at 1:28 AM , Anonymous Facts Ride LLC said...

THanks for sharing! Great Piece of content.
Do check ma website- Factsride.com

 
At August 29, 2022 at 11:04 AM , Blogger raju said...

wordpress design services agency Need professional WordPress Web Design Services? We're experts in developing attractive mobile-friendly WordPress websites for businesses. Contact us today!

 

Post a Comment

Subscribe to Post Comments [Atom]

<< Home