Setting Short Value Java

有些话、适合烂在心里 提交于 2019-12-17 06:14:25

问题


I am writing a little code in J2ME. I have a class with a method setTableId(Short tableId). Now when I try to write setTableId(100) it gives compile time error. How can I set the short value without declaring another short variable?

When setting Long value I can use setLongValue(100L) and it works. So, what does L mean here and what's the character for Short value?

Thanks


回答1:


In Java integer literals are of type int unless they are suffixed with letter 'L' or 'l' (Capital L is preferred as lower case L is hard to distinguish from number 1). If suffixed with L, the literals are of type long.

The suffix does not have any special name in the Java Language Specification. Neither is there suffixes for any other integer types. So if you need short or byte literal, they must be casted:

byte foo = (byte)0;
short bar = (short)0;

In setLongValue(100L) you don't have to necessarily include L suffix because in this case the int literal is automatically widened to long. This is called widening primitive conversion in the Java Language Specification.




回答2:


There is no such thing as a byte or short literal. You need to cast to short using (short)100




回答3:


You can use setTableId((short)100). I think this was changed in Java 5 so that numeric literals assigned to byte or short and within range for the target are automatically assumed to be the target type. That latest J2ME JVMs are derived from Java 4 though.




回答4:


Generally you can just cast the variable to become a short.

You can also get problems like this that can be confusing. This is because the + operator promotes them to an int

Casting the elements won't help:

You need to cast the expression:



来源:https://stackoverflow.com/questions/2294934/setting-short-value-java

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