Floating-point Literals in java

Java Programming Language Variables in java (Article) Variables in java (Program)

2718

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:

 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.


This Particular section is dedicated to Programs only. If you want learn more about Java Programming Language. Then you can visit below links to get more depth on this subject.