21

I was wondering why we can do:

Long l = 2L;
Float f = 2f;
Double d = 2d;

or even

Double d = new Double(2);

and not

Short s = 2s; //or whatever letter it could be

nor

Short s = new Short(2); //I know in this case 2 is an int but couldn't it be casted internally or something?

Why do we need to take the constructors either with a String or a short.

Nuno Gonçalves
  • 6,202
  • 7
  • 46
  • 66
  • 3
    There are no short nor byte literals in Java. – Eng.Fouad Jul 17 '12 at 16:06
  • @Eng.Fouad is correct. 0xFF is an int in java, the >> and << operators take and return ints, shorts and bytes are just left a bit to one side. No idea why though. – lynks Jul 17 '12 at 16:08
  • https://stackoverflow.com/questions/317816/why-are-there-no-byte-or-short-literals-in-java – deldev Aug 15 '22 at 02:28

2 Answers2

15

But you can do this:

Short s = 2;

Or this:

Short s = new Short((short)2);

Or this:

Short s = new Short("2");

Any of the above will work as long as the number is in the range [-2^15, 2^15-1]

Óscar López
  • 232,561
  • 37
  • 312
  • 386
  • 1
    Actually you can't do Short s = new Short((short) 2); Either that or my eclipse is wrong. You need to use short short = 2; and than use it on the constructor. – Nuno Gonçalves Jul 17 '12 at 16:22
4

One of the main rules in Java is that any mathematical operation's result will be stored in a large size variable to avoid truncation. For example if you are adding int with long the result will be long. Hence, any operation on byte, char, or short will result an int even if you added 1 to a byte.There are 2 ways to store the result in the same data type:

a) you do explicit casting:

short s=10;  
s=(short)(s+1);  

b) You can use the auto increment of short hand operations to ask the JVM to do implicit casting:

short s=10;  
s+=21;  

OR

short s=10;  
s++;  

if you need short or byte literal, they must be casted as there is no suffix like S or s for short:

byte foo = (byte)100000;
short bar = (short)100000;
Lion
  • 18,729
  • 22
  • 80
  • 110
  • Even adding two `short`s or `byte`s or `char`s will result in an `int`. While adding two `int`s will not result in a `long`. `int` is just special here. Which is another reason why `DataOutput#writeShort` takes an int parameter instead of short. – mihi Jul 17 '12 at 16:32