Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why don't we add an "s" suffix to short types?

Tags:

java

Why don't we write s with short data type like short s = 2s; as we write with float e.g float f = 1.23f?

I know when we write float by default the compiler treats it as double and assigns 8 temporary bytes to it, and when it tries to copy that 8 byte to float's 4 that results in a type error, so that is why we write f after initializing a float, but why we don't do something similar with short as by default int is a literal type?

like image 826
PVP Avatar asked Jun 16 '17 20:06

PVP


People also ask

Why does r use L for integers?

Because R's integers are 32-bit long integers and "L" therefore appears to be sensible shorthand for referring to this data type.

Is 0L long?

The 0L means the number zero of type long . It uses this constructor to instantiate a Date that refers to zero milliseconds after (i.e. exactly) "the epoch", January 1, 1970, 00:00:00 GMT.


2 Answers

The Java Language Specification allows a type suffix of L or l for long literals. However, it does not provide a type suffix for short values. It's not necessary because:

  • Any value that could be represented by a short can also by represented by the default integral type int.
  • Assignments of an int value to a short variable are allowed if the value is a constant expression, whose value can be represented by a short. See the Java Language Specification, "Assignment Contexts":

A narrowing primitive conversion may be used if the type of the variable is byte, short, or char, and the value of the constant expression is representable in the type of the variable.

like image 98
Andy Thomas Avatar answered Oct 04 '22 15:10

Andy Thomas


Why don't we add an “s” suffix to short types?

Because the Java language is inconsistent on this point.

The JLS is more flexible for no floating numeric primitive types as for floating numeric primitive types :

In addition, if the expression is a constant expression (§15.28) of type byte, short, char, or int:

A narrowing primitive conversion may be used if the type of the variable is byte, short, or char, and the value of the constant expression is representable in the type of the variable.

I think that doing a distinction between byte, short, char, or int and float and double in the way to declare and manipulate them was not really required. It creates inconsistency and so potential mistakes in the use of them.

if short s = 10; is valid because the narrowing primitive conversion is validated by the compiler that it has no lost information, so float f = 10.0; would also have been valid for exactly the same reason.

like image 27
davidxxx Avatar answered Oct 04 '22 15:10

davidxxx