Java strictfp Keyword



The strictfp keyword is a modifier that stands for strict floating point. As the name suggests, it ensures that floating-point operations give the same result on any platform. This keyword was introduced in Java version 1.2.

In Java, the floating point precision may vary from one platform to another. The strictfp keyword solves this issue and ensures consistency across all platforms.

With the release of Java 17 version, the strictfp keyword is no longer needed. Regardless of whether you use this keyword, the JVM now provides consistent results for floating-point calculations across different platforms.

When to use Java strictfp keyword?

The strictfp keyword can be used with class, method, and interfaces but cannot be applied to abstract methods, variable and constructors.

Furthermore, if strictfp modifier is used with a class or an interface, then all methods declared in that class and interface are implicitly strictfp.

Following are the valid strictfp usage ?

// with class
strictfp class Test {
   // code
}
// with interface
strictfp interface Test {
   // code
}
class A {
   // with method inside class    
   strictfp void Test() {
      // code
   }
}

Following are the invalid strictfp usage ?

class A {
   // not allowed with variable    
   strictfp float a;
}
class A {
   // not allowed with abstract method
   strictfp abstract void test();
}
class A {
   // not allowed with constructor
   strictfp A() {
      // code
   }
}

Example of Java strictfp keyword

The following example demonstrates the usage of strictfp keyword. Here, the addition() method in the Calculator class will perform the addition with strict floating-point precision.

// class defined with strictfp keyword
strictfp class Calculator {
   public double addition(double num1, double num2) {
      return num1 + num2;
   }
}
// Main class
public class Main {
   public static void main(String[] args) {
      // creating instance
      Calculator calc = new Calculator();
      // method call
      System.out.println(calc.addition(5e+10, 6e+11));
   }
}

When you execute the above code, result will be displayed along with a warning message as the strictfp keyword is not required from Java 17.

6.5E11
Updated on: 2024-07-31T17:27:39+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements