Results 1 to 5 of 5

Thread: function overloading: call to short method calls int method

  1. #1
    Join Date
    Jun 2008

    function overloading: call to short method calls int method

    Hi all,

    I have a doubt regarding function overloading. I have three functions which has arguments as short, int and long. A function call to short, calls the method with the int argument. why does it happen?

    public class longshort
    public static void go(Long n){System.out.println("Long  ");}
    public static void go(Short n){System.out.println("Short  ");}
    public static void go(int n){System.out.println("int  ");}
    public static void main(String args[])
    short y=6;
    long z=7;
    The output of this code is:
    int Long

    Can anyone please explain me?

  2. #2
    Join Date
    Nov 2008
    Its a problem of typecast
    U gave Wrapper class Short as function argument and defined a variable as type short.

    U may get technical note on http://java.sun.com/j2se/1.5.0/docs/...ang/Short.html

    Jithesh PM

  3. #3
    Join Date
    Jun 2008
    Hello axxonet,

    I am not able to clearly understand. I am passing short as the argument. Then why the function for int get invoked. Can you please tell me the conditions in which these type casts will take place. Which type will be casted to which type?

  4. #4
    Join Date
    Nov 2008
    Hai vaishnavi,

    I think the reason is this. The 'short' type is a 16-bit signed two's complement integer.The java compiler acts short value as a integer type unless you are explicitly specified (Higher order).

    In your class , the 'go' method have no argument that receive a parameter of type short. You have given Short wrapper class instead.
    If you changed to short

    public static void go(short n){System.out.println("Short ");} It will work fine.
    else it will read
    public static void go(int n){System.out.println("int ");}.

    But if you comment the above 'int' method then it will invoke the 'Short' method.

    This case is applicable for 'byte' type also.
    So short and byte are having this behaviour.

    You will get more information by looking Java Primitives variables.

  5. #5
    Join Date
    Aug 2005
    The Garden State
    actually the behavior's true of any primitive wrapper, it'll favor the up convert to the other primitive before the autobox.
    Acceptable Use | SQL Forum FAQ | celery is tasteless | twitter

    celery is tasteless - currently needing some UI time

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
HTML5 Development Center