Java Top

The early-bird price of the new Learn Spring Security OAuth course packages will increase by $50 tomorrow:

>> CHECK OUT THE COURSE

1. Introduction

By default, the floating-point computations in Java are platform-dependent. And so, the floating-point outcome's precision depends on the hardware in-use.

In this tutorial, we'll learn how to use strictfp in Java to ensure platform-independent floating-point computations.

2. strictfp Usage

We can use the strictfp keyword as a non-access modifier for classes, non-abstract methods or interfaces:

public strictfp class ScientificCalculator {
    ...
    
    public double sum(double value1, double value2) {
        return value1 + value2;
    }

    public double diff(double value1, double value2) { 
        return value1 - value2; 
    }
}

public strictfp void calculateMarksPercentage() {
    ...
}

public strictfp interface Circle {
    double computeArea(double radius);
}

When we declare an interface or a class with strictfp, all of its member methods and other nested types inherit its behavior.

However, please note that we're not allowed to use strictfp keyword on variables, constructors or abstract methods.

Additionally, for cases when we have a superclass marked with it, it won't make our subclass inherit that behavior.

3. When to Use?

Java strictfp keyword comes handy whenever we care a great deal about the deterministic behavior of all floating-point computations:

@Test
public void whenMethodOfstrictfpClassInvoked_thenIdenticalResultOnAllPlatforms() {
    ScientificCalculator calculator = new ScientificCalculator();
    double result = calculator.sum(23e10, 98e17);
    assertThat(result, is(9.800000230000001E18));

    result = calculator.diff(Double.MAX_VALUE, 1.56);
    assertThat(result, is(1.7976931348623157E308));
}

Since the ScientificCalculator class makes use of this keyword, the above test case will pass on all hardware platforms. Please note that if we don't use it, JVM is free to use any extra precision available on the target platform hardware.

A popular real-world use-case for it is a system performing highly-sensitive medicinal calculations.

4. Conclusion

In this quick tutorial, we talked about when and how to use the strictfp keyword in Java.

As usual, all the presented code samples are available over on GitHub.

Java bottom

The early-bird price of the new Learn Spring Security OAuth course packages will increase by $50 tomorrow:

>> CHECK OUT THE COURSE

Leave a Reply

avatar
  Subscribe  
Notify of