Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does declaring a Java class strictfp mean methods it calls in other classes are also strictfp?

Tags:

java

strictfp

As title really... if class X is declared strictfp and calls methods in class Y, will strictness be enforced, or does this only apply to X's own code?

Additionally, if I calculate a value in a strictfp class method and pass it into a non-strictfp method, is the value still 'safe' if no further calculations are done with it?

like image 697
Mr. Boy Avatar asked Jun 11 '13 19:06

Mr. Boy


People also ask

Is it possible to declare a variable with strictfp?

strictfp Usage 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.

Why do we use strictfp?

strictfp is used to ensure that floating points operations give the same result on any platform. As floating points precision may vary from one platform to another. strictfp keyword ensures the consistency across the platforms.

Which of the following techniques can be used to ensure that code in a Java SE class conforms to the IEEE 754 standard for floating point calculations?

In Java, the strictfp keyword is used to force the precision of floating point calculations (float or double) in Java conform to IEEE's 754 standard, explicitly.


2 Answers

As far as I understand strictfp is limited to scope marked with this keyword. This means that it causes calculations of marked class or method to be portable.

It cannot propagate the effect to referenced code. For example if foo() is strictfp but it calls bar() from some other class that is not strictfp, the calculations inside bar() will not be portable, but calculations inside foo() will be. So, if results of bar() are used in foo() the overall result might be not portable.

public strictfp double foo() {
    return bar() * 3.1415926;
}
public double bar() {
    return 2.718281828 * 2.0;
}

This result 2.718281828 * 2.0 is not portable, but its multiplication by 3.1415926 is.

like image 110
AlexR Avatar answered Oct 07 '22 13:10

AlexR


From the Java Language Specification:

The effect of the strictfp modifier is to make all float or double expressions within the class declaration (including within variable initializers, instance initializers, static initializers, and constructors) be explicitly FP-strict.

[my emphasis]

like image 21
user207421 Avatar answered Oct 07 '22 12:10

user207421