Java instantiate Short object in Java

Nuno Gonçalves picture Nuno Gonçalves · Jul 17, 2012 · Viewed 19.5k times · Source

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.

Answer

Óscar López picture Óscar López · Jul 17, 2012

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]