Strictfp keyword in java

Strictfp keyword

Sctrictfp : 

It is a keyword in java which is used to make a the common precision for floating type which differs from platform to platform .

Strictfp can be used at three levels :
  1. Class Level
  2. Interface Level 
  3. Method Level. 

Syntax for class Level:

strcitfp class <ClassName>
{
     varibales;
     
     methods();
}

Syntax for Interface Level:

strictfp interface <interface Name>
{
     final variables;

     abstract methods();
}

Syntax for method level:

class <class Name>
{

   variables ;

    strictfp <return type> <method name>

}

Program using Strictfp at class level


strictfp class StrictfpClass

{

float value=10.2f;

void add()
{
value=10+value;

System.out.println(value);
}
}

class Strictfp 
{
public static void main(String[] args) 
{
StrictfpClass sc=new StrictfpClass();

sc.add();
}
}

Save As:

Strictfp.java

Compile As:

javac Strictfp.java

Run As:

java Strictfp

Output:

20.2

Note :

The above output obtained will be common on any platform  with same precision.Here all the methods present inside the strictfp class will be strictfp methods .

Program using Strictfp at method level

class Strictfp
{
float value=10.2f;

strictfp void add()
{
value=10+value;

System.out.println(value);
}

void sub()
{
value=value-10;

System.out.println(value);
}
}

class StrictfpMethod 
{
public static void main(String[] args) 
{
Strictfp sc=new Strictfp();

sc.add();

sc.sub();
}

}

Save As:

StrictfpMethod.java

Compile As:

javac StrictfpMethod.java

Run As:

java StrcitfpMethod

Output:

20.2
10.200001

Note :

Here add() method is strictfp method hence the output is common on any platform but the sub() is not strictfp method hence there may be different output on different platform.

Strictfp where we cant apply are as follows:


  1. we cant apply strictfp keyword for constructor.
  2. we cant apply strctfp keyword for a variable 
  3. we cant apply strictfp keyword for abstract methods.
Note :

If we apply strcitfp at constructor or variable  jvm throws a exception "modifier strictfp will not be allowed here ".

If we apply strictfp at abstract method then JVM throws exception " illegal combination of modifiers ".


Comments

Popular posts from this blog

Programs on Inheritance

Arrays In Java

Java Inner Classes