strictfp keyword in java
The "strictfp"
keyword in Java is used to force the precision of floating point calculations (both float and double) in Java conform to IEEE standard, explicitly.
If we don’t use strictfp
keyword, the floating point precision value will be taken from the target platform’s hardware, i.e. CPU’s floating point processing capability.
In other words, If we use strictfp
, result of floating point computations will be always same on all the platforms.
Since precision may differ from platform to platform ,Java programming language have provided the strictfp
keyword, using which we can get the same result on all the platforms.
The
strictfp
keyword can be applied on methods, classes and interfaces.
- strictfp class StrictFPClassExample {
- double num1 = 20e+50;
- double num2 = 25e+10;
- double add() {
- return num1 + num2;
- }
- }
strictfp class StrictFPClassExample { double num1 = 20e+50; double num2 = 25e+10; double add() { return num1 + num2; } }
In the above example, all the floating point or double number computations within that class conform to IEEE standard
- strictfp interface StrictFPInterfaceExample {
- double add();
- }
strictfp interface StrictFPInterfaceExample { double add(); }
In the above example, strictfp
is applied on interface.
- class StrictFPMethodExample {
- strictfp double add(double num1, double num2) {
- return num1 + num2;
- }
- }
class StrictFPMethodExample { strictfp double add(double num1, double num2) { return num1 + num2; } }
In the above example,
strictfp
is applied on specific method in the class.
Rules for
strictfp
keywordThe
strictfp
keyword can’t be applied on abstract methods, variables or constructors.
- class StrictFPAbstractExample {
- strictfp abstract void add(double num1,double num2);//Illegal modifier
- }
class StrictFPAbstractExample { strictfp abstract void add(double num1,double num2);//Illegal modifier }
- class StrictFPVariableExample {
- strictfp double amount=100.123;//modifier strictfp not allowed here
- }
class StrictFPVariableExample { strictfp double amount=100.123;//modifier strictfp not allowed here }
- class StrictFPConstructorExample {
- strictfp StrictFPConstructorExample(){}//modifier strictfp not allowed here
- }
class StrictFPConstructorExample { strictfp StrictFPConstructorExample(){}//modifier strictfp not allowed here }
The
strictfp
keyword can not be applied on any methods in interface.
- strictfp interface StrictFPInterface {
- strictfp double multiply(); // compile error
- }
strictfp interface StrictFPInterface { strictfp double multiply(); // compile error }
Why
As different platforms have different floating point hardware which calculates with more precision and greater range of values than the java specification requires which may produce diffrent output on diffrent plateforms.so it confirms the same output irrespective of diffrent plateforms.
strictfp
is used ?