strictfp modifier in Java

In Java, floating point representations and computations are platform dependent. strictfp modifier ensures that all floating-point operations across different JVMs and platforms will provide consistent and same result predicted by IEEE 754.

When we use strictfp, JVM performs floating-point computations using values that can be represented by a standard Java float or double, guaranteeing that the result of the computations will match exactly across all JVMs and platforms.

1. How to use strictfp modifier

The strictfp modifier can be used with –

  1. class – All code in the class (instance, variable, static initializers), and code in nested classes will use strictfp computations.
  2. method – All code within method will use strictfp computations.
  3. interface – All code in any class that implements the interface will use strictfp computations.

strictfp keyword cannot be used with abstract classes and method.

Please nore that strictfp behavior is not inherited by a subclass that extends a strictfp superclass. An overriding method can independently choose to be strictfp while the overridden method is not, or vice versa.

2. Java strictfp example

Let’s see an example of strictfp modifier for floating point comparisons which will yield exactly same result in all the platforms and processor architectures.

In given example, we have used Double.MAX_VALUE value which is a very big number and has different representations in each platform. Using strictfp, we can ensure that given calculation will always result in same value.

public strictfp class Main 
{
	public static void main(String[] args) 
	{
		double MAX = Double.MAX_VALUE;
		
		System.out.println(Double.MAX_VALUE - 1);
	}
}

Program output.

1.7976931348623157E308

Drop me your questions related to strictfp keyword in Java.

Happy Learning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

2 thoughts on “strictfp modifier in Java”

  1. Hello Thank you for explanation,

    How this strictfp results platform independent. could you please explain more.

    Thanks,
    Vikram.

    Reply

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.