0

I added a Byte variable to a Short variable, however I had to add (Short) for the line of code to compute. I thought this was not needed as I'm adding a smaller data type to a bigger one. Why is this?

What i thought was correct.

        byte NumberOfShoes = 5;
        short Laces = 10;
        short ShoePacks = NumberOfShoes + Laces;
        System.out.println(ShoePacks);

What was correct.

        byte NumberOfShoes = 5;
        short Laces = 10;
        short ShoePacks = (short) (NumberOfShoes + Laces);
        System.out.println(ShoePacks);
icrovett
  • 435
  • 7
  • 21
Kennszo
  • 1
  • 1
  • 1
    Does this answer your question? [Promotion in Java?](https://stackoverflow.com/questions/1660856/promotion-in-java) (the duplicate is mainly about bytes, but the same things happen here: operands are converted to `int` and then added) – harold Nov 04 '22 at 10:06
  • *tl;dr* `byte` and `short` are not general purpose numeric variables in Java and will be hard to use for stuff like that. Just use `int` and cast down were necessary (plus probably checking for overflow). – Joachim Sauer Nov 04 '22 at 15:10

0 Answers0