Setting Short Value Java

后端 未结 4 606
死守一世寂寞
死守一世寂寞 2020-11-28 11:36

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 compil

相关标签:
4条回答
  • 2020-11-28 12:14

    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.

    0 讨论(0)
  • 2020-11-28 12:16

    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:

    0 讨论(0)
  • 2020-11-28 12:21

    In Java, integer literals are of type int by default. For some other types, you may suffix the literal with a case-insensitive letter like L, D, F to specify a long, double, or float, respectively. Note it is common practice to use uppercase letters for better readability.

    The Java Language Specification does not provide the same syntactic sugar for byte or short types. Instead, you may declare it as such using explicit casting:

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

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

    0 讨论(0)
  • 2020-11-28 12:25

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

    0 讨论(0)
提交回复
热议问题