Google+

198. Storing floating point literals in float data type variables







Theoretically Literals means any number, text or other information that represents a value.

By default, the Floating Point Literals data type is double. i.e. The compiler considers the decimal values as double type.

As the Java compiler considers the decimals values (i.e. Floating Point Literals) as double type by default, the following example with throw Compiler errors while assigning decimal values to the float data type variable.

Lets implement this on Eclipse IDE -

1. Launch Eclipse IDE, create a Java Project 'Project 29' as shown below -


2. Create a Java Class 'ClassOne' as shown below -


3. Assign a decimal value say '1.2' to a float data type variable as shown below -


4. View the error message as shown below -


Hence the assigned decimal value (i.e. floating point literal) is considered as double type by default. As we cant assign a double type value to a float type variable, we are getting this error.

In order to overcome this problem, we have to tell the compiler that the assigned value is a float type value, by specifying a letter 'F' at the end of the literal as shown below and observe that the error got resolved -


Now after specifying the letter 'F' after the decimal value, the compiler treats the Floating Point literal (decimal value) as float type. If not specified with a letter 'F' after the literal, compiler by default will treat the Floating point literal (decimal value) as double type and will throw errors when assigned to float type variables.




Please comment below to feedback or ask questions.

Using character escape sequences in String literals will be explained in the next post.







No comments: