Home / Programs / Floating-point Literals in java
Programming Example

Floating-point Literals in java

👁 2,826 Views
💻 Practical Program
📘 Step by Step Learning
Floating-point Literals in java

Information & Algorithm

This is a Java program that demonstrates the use of a float literal. In Java, a float literal is a number with a decimal point, followed by the letter f or F to indicate that it is a float type.

The program declares a float variable named ff and assigns it the value 99.0f. This value is a float literal that represents the decimal value 99.0 as a float type.

The program then prints the value of ff to the console using the System.out.println method. When run, the program will output the value of ff, which is 99.0.

Program Code

 public class FloatLiteral {

  public static void main(String[] a) {

    float ff = 99.0f; //OK
    System.out.println(ff);

  }

}

/*

Floating-point literals in Java default to double precision.
To specify a float literal, you must append an F or f to the constant.
You can also explicitly specify a double literal by appending a D or d.

float f = 99.0; // Type mismatch: cannot convert from double to float
float ff = 99.0f; //OK

double dou = 99.0D; //OK
double doub = 99.0d; //OK
double doubl = 99.0; //OK, by default floating point literal is double

*/

Output

99.0
Press any key to continue . . .

Explanation

In summary, this program demonstrates how to use a float literal to assign a value to a float type variable in Java. Note that if you do not include the f or F at the end of the literal, Java will interpret it as a double type instead.

How to learn from this program

First read the algorithm, then study the program code line by line. After that, compare the code with the output and finally go through the explanation. This approach helps learners understand both the logic and the implementation properly.