Win a copy of Java 9 Modularity: Patterns and Practices for Developing Maintainable Applications this week in the Java 9 forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Method overloading  RSS feed

 
Anurag Malaviya
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This code is from SCJP guide from seira and berts
Please explain me the output of the following code:

public class Bertha{
static String s="";
public static void main(String args[])
{
int x=4;
Boolean y=true;
short [] sa={1,2,3};
doStuff(x,y);
doStuff(x);
doStuff(sa,sa);
System.out.println(s);
}
static void doStuff(Object o)
{
s+="1";
}
static void doStuff(Object... o)
{
s+="2";
}
static void doStuff(Integer...i)
{
s+="3";
}
static void doStuff(Long l)
{
s+="4";
}

The output of the code is 212
When the doStuff method is called second time,an integer variable is passed
to the method,but still the method with Object argument is called instead of method
with var-args of Integer?Can anyone explain this behaviour?
 
Neha Daga
Ranch Hand
Posts: 504
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
because var args are chosen the last that is if no other options is available then only var args version will be chosen.

widening is prefered over boxing.
boxing is prefered over var args.

so int will be boxed and then widened to Object rather than boxing and chosing var args.

this might help you.
 
Ankit Garg
Sheriff
Posts: 9610
37
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Anurag please Use Code Tags when you post a source code. That way your code looks formatted. Unformatted code is hard to read. You can add code tags by wrapping your code in [code] [/code] tags. You can edit your message using button and then add code tags to it...
 
Anurag Malaviya
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Neha Daga wrote:because var args are chosen the last that is if no other options is available then only var args version will be chosen.

widening is prefered over boxing.
boxing is prefered over var args.

so int will be boxed and then widened to Object rather than boxing and chosing var args.

this might help you.

Thanks for helping me out.........
I am also looking for working on a project.
But i am not able to decide,whether i should work on web based project or a project that involves networking
please suggest
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!