Results 1 to 4 of 4

Thread: short + short = int????

  1. #1

    Thread Starter
    Frenzied Member agmorgan's Avatar
    Join Date
    Dec 2000
    Location
    Lurking
    Posts
    1,383

    short + short = int????

    This is crazy, I am trying to add 2 shorts together and I get an int!
    Code:
          short a = 1;
          short b = 2;
          short c;
          c = a + b;
    Why do I have to cast to a short when all the variables are already shorts?
    Code:
    c = (short) (a + b);
    Is there any rationale behind this?

  2. #2
    Arabic Poster ComputerJy's Avatar
    Join Date
    Nov 2005
    Location
    Happily misplaced
    Posts
    2,513

    Re: short + short = int????

    short + short might be an int, right?
    This is why the Java compiler considers the sum of 2 shorts as an int.
    There is a solution to this problem - and by the way it's not that much of a problem - , a simple command line argument when compiling But I can't seem to remember it.
    "I'm not normally a praying man, but if you're up there, save me... Superman!" - Homer Simpson
    My Blog

  3. #3

    Thread Starter
    Frenzied Member agmorgan's Avatar
    Join Date
    Dec 2000
    Location
    Lurking
    Posts
    1,383

    Re: short + short = int????

    Quote Originally Posted by ComputerJy
    short + short might be an int, right?
    This is why the Java compiler considers the sum of 2 shorts as an int.
    int + int might be a long but the Java compiler doesn't consider the sum of 2 ints as a long though.
    Seems strange that it doesn't automatically try to cast it back down to a short if it can.
    I'd be interested in that compiler option if you can manage to dig it out.

  4. #4
    Arabic Poster ComputerJy's Avatar
    Join Date
    Nov 2005
    Location
    Happily misplaced
    Posts
    2,513

    Re: short + short = int????

    Java Lang Specs says:
    ‘Binary numeric promotion is performed on the operands (§5.6.2). The type of a
    multiplicative expression is the promoted type of its operands. If this promoted type is
    int or long, then integer arithmetic is performed; ...If an integer multiplication overflows,
    then the result is the low-order bits of the mathematical product as represented in some
    sufficiently large two’s-complement format. As a result, if overflow occurs, then the sign of
    the result may not be the same as the sign of the mathematical product of the two operand
    values.’


    In reality Java performs Integer summation on int and long data types only

    If you want more about this topic you can read this paper
    "I'm not normally a praying man, but if you're up there, save me... Superman!" - Homer Simpson
    My Blog

Posting Permissions

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



Click Here to Expand Forum to Full Width