Java instantiate Short object in Java

隐身守侯 提交于 2019-11-29 05:48:11

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]

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;
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!