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

3

6

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?

Shang answered 11/6, 2013 at 19:57 Comment(0)
Q
4

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.

Quan answered 11/6, 2013 at 20:8 Comment(2)
I don't even know what portable means.Rank
If you run this code somewhere else - the result will be always the same, no matter what OS you use or what processor etc.Barbados
M
2

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]

Masson answered 11/6, 2013 at 23:53 Comment(0)
J
0

It only applies to expressions in methods declared in that class.

From the jGuru article What is the strictfp modifier for? When would I consider using it?:

The strictfp keyword may be applied to both classes and methods. For classes (and interfaces), it specifies that all of the expressions in all of the methods of the class are FP-strict.

To answer your second question: yes, a floating point value will be "safe" once it's no longer subject to further calculations, since strictfp applies only to expressions.

Related: When should I use the "strictfp" keyword in java?

Joshia answered 11/6, 2013 at 20:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.