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 !!

Comments

Subscribe
Notify of
guest

2 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.