Autoboxing - programming concept

75 views Asked by At
1. public static void main(String[] args) 
2. {        
3.    Character s=1;
4.    Float f=1;
5. }

Both the lines 3 and 4 have a wrapper class and compiler performs autoboxing to convert 1 to Character but compiler cannot convert the same 1 to Float. Why?

2

There are 2 answers

1
Prabhakaran Ramaswamy On

Float numbers you need to append 'f' or 'F' at end of the number like this Float f=1f; or Float f=1F;

0
Rahul On

That is because, by default it would be a double. You need to suffix a float number with F or f to make it a float. Ex: Float f = 1f;

§JLS 3.10.2:

A floating-point literal is of type float if it is suffixed with an ASCII letter F or f; otherwise its type is double and it can optionally be suffixed with an ASCII letter D or d (§4.2.3).