0

The code below is resulted to the compiler error in java

float variable = 123.4

And it is because of the fact that the default for the floating point literal value is Double data type. So, we should cast the literal value to the float in advance or declare the variable as double in order to solve this issue. As we know the default for the integer literal value is Integer data type. However, there is no compiler error when we declare a Byte variable like the example below

byte variable = 123

I want to know why we do not have to cast 123 to Byte data type if the default for integral literal value is integer.

moha
  • 579
  • 2
  • 9
  • 27
  • 2
    You don't have to cast if you write `float variable = 123.4f` – janos Jul 16 '17 at 09:50
  • 3
    There is no loss of precision storing `123` as a `byte` – khelwood Jul 16 '17 at 09:51
  • I agree with @janos However, it's a common convention to use uppercase letters when initializing literals. – Jacob G. Jul 16 '17 at 09:52
  • 1
    This is just how Java works. If you want to know the exact rules, see [paragraph 5.2](https://docs.oracle.com/javase/specs/jls/se8/html/jls-5.html#jls-5.2) of the Java Language Specification. – Jesper Jul 16 '17 at 09:54
  • @khelwood yes, 123 can exactly represent by a byte, and it is the question, if the default for integer literal value is int, why we do not have to cast 123 to byte in order to assign it to a byte variable – moha Jul 16 '17 at 10:01

1 Answers1

0

Values of the integral types byte, short, int, and long can be created from int literals while the value fit into the type of the variable.

You can retrieve the information here.

So this :

byte variable = 123;

is fine as 123 fits to a byte.

But byte variable = 1000;

will not compile as 1000 doesn't fit into a byte.

davidxxx
  • 125,838
  • 23
  • 214
  • 215
  • I think `123.4D` also fits to a float. –  Jul 16 '17 at 10:00
  • @saka1029 It doesn't specify float and `123.4D` is not an int literal. – davidxxx Jul 16 '17 at 10:01
  • There is no doubt that we can declare a floating point literal value like this float variable=1.4 and although 1.4 is completely fit into the float data type, there is steal a compiler error and we have to cast 1.4 to the float data type in java – moha Jul 16 '17 at 10:06