Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java instantiate Short object in Java

Tags:

java

short

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.

like image 537
Nuno Gonçalves Avatar asked Jul 17 '12 16:07

Nuno Gonçalves


People also ask

How do you initialize an object in Java?

Creating an Object Declaration − A variable declaration with a variable name with an object type. Instantiation − The 'new' keyword is used to create the object. Initialization − The 'new' keyword is followed by a call to a constructor. This call initializes the new object.

What is shorting in Java?

The short class wraps a primitive short type value in an object. Its object contains only a single field whose type is short.

Are there shorts in Java?

An object of type Short contains a single field whose type is short . In addition, this class provides several methods for converting a short to a String and a String to a short , as well as other constants and methods useful when dealing with a short .


2 Answers

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;
like image 36
Lion Avatar answered Sep 29 '22 18:09

Lion


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]

like image 77
Óscar López Avatar answered Sep 29 '22 18:09

Óscar López