0

In java Numeric have 2 categories - Integer and Floating. For Integer default value is int whereas for floating the default value is double.

So to declare and initialize a float variable you need to use:

    float floatVar=10.0F; 

Here use of F or f postfix is mandatory as by default the value will be treated as double.

While to declare and initialize integer long you can use:

    long longVar=10L; or long longVar=10;

The above is consistent with floating variables as default is considered as int so you need to tell compiler that treat this as long value not as int. Also as int is subset of long so without using L or l as postfix is acceptable.

Now say you need to declare and initialize a short variable you can use:

    short shortVar=10;

Here there is no need to use anything as postfix to tell compiler that treat it as a short variable value rather than default int value. I understand that the value is within the range of short variable's defined range and I also understand implicit casting when the destination is larger to hold the value. But why there is inconsistent behavior when dealing with integral and floating variables?

Har Krishan
  • 273
  • 1
  • 11
  • 1
    The short answer is: because [JLS ยง5.2](https://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html#jls-5.2) says so. It is a design decision. The discrimination between `float` and `double` is less intuitive (for humans) than the discrimination between integer (i.e. whole numbers). My speculation is that this is the most comfortable way for the programmer to assign a value to a primitive of type `byte`, `short` and `char`(but you should never really assing a number to a char anyway). โ€“ Turing85 Jan 11 '18 at 10:36
  • The above link is not answer to my question which explains about casting which I understand completely. โ€“ Har Krishan Jan 11 '18 at 10:44
  • @Turing85 I agree to your comment that it is a design decision and also assuming the facts behind this decision as you mentioned. char is a +ve subset of integer so we can assign +ve integer value (no doubt it should be within the defined range limit) to char. โ€“ Har Krishan Jan 11 '18 at 10:47

0 Answers0