What is Native modifier in Java?

What is Native modifier in Java?

What is Native modifier in Java?

What is Native modifier in Java?
  • Native is the modifier applicable only to the method and we can’t apply anywhere else.
  • The method which is implemented in non-java(mostly c and c++) are called native methods or foreign methods.
  • The main objectives of a native keyword are
    1. To improve the performance of the system
    2. To achieve machine level or memory level communication
    3. To use already existing legacy non-java code.
  • For a native method, implementation is already available in c or c++ and we are not responsible to provide implementation hence native method declaration should end with a semicolon.
  • Example:-Public native void m1();
  • For a native method, implementation is already available in old language but for an abstract method, the implementation should not be available hence we can’t declare a native method as abstract i.e. Native-abstract combination is an illegal combination for methods.
  • Native methods were used in the past to write performance critical sections but with Java getting faster this is now less common. Native methods are currently needed when
    • You need to call a library from Java that is written in other languages.
    • You need to access system or hardware resources that are only reachable from the other language (typically C). Actually, many system functions that interact with the real computer (disk and network IO, for instance) can only do this because they call native code.
  • We can’t declare native methods as strictfp because there is no guarantee that old language follows IEEE754 standard hence native-strictfp combination is an illegal combination of the method.
  • The main advantage of a native keyword is performance will be improved but the main disadvantage of a native keyword is it breaks platform independent nature of java.
Pseudo code to use the native keyword in Java:
package com.java4us

Class Native
{
    Static
    {
        System.LoadLibrary(“Native library path”);
    }
    Public native void m();
}
Class Test
{
    Public static void main(String[] args)
    {
        Native n = new Native();
        n.m();
    }
}

 

Leave a Reply

Your email address will not be published. Required fields are marked *

*